users_controller.rb 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112
  1. # Copyright (C) 2012-2016 Zammad Foundation, http://zammad-foundation.org/
  2. class UsersController < ApplicationController
  3. include ChecksUserAttributesByCurrentUserPermission
  4. prepend_before_action :authentication_check, except: %i[create password_reset_send password_reset_verify image]
  5. prepend_before_action :authentication_check_only, only: [:create]
  6. # @path [GET] /users
  7. #
  8. # @summary Returns a list of User records.
  9. # @notes The requester has to be in the role 'Admin' or 'Agent' to
  10. # get a list of all Users. If the requester is in the
  11. # role 'Customer' only just the own User record will be returned.
  12. #
  13. # @response_message 200 [Array<User>] List of matching User records.
  14. # @response_message 401 Invalid session.
  15. def index
  16. offset = 0
  17. per_page = 500
  18. if params[:page] && params[:per_page]
  19. offset = (params[:page].to_i - 1) * params[:per_page].to_i
  20. per_page = params[:per_page].to_i
  21. end
  22. if per_page > 500
  23. per_page = 500
  24. end
  25. # only allow customer to fetch him self
  26. users = if !current_user.permissions?(['admin.user', 'ticket.agent'])
  27. User.where(id: current_user.id).order(id: 'ASC').offset(offset).limit(per_page)
  28. else
  29. User.all.order(id: 'ASC').offset(offset).limit(per_page)
  30. end
  31. if response_expand?
  32. list = []
  33. users.each do |user|
  34. list.push user.attributes_with_association_names
  35. end
  36. render json: list, status: :ok
  37. return
  38. end
  39. if response_full?
  40. assets = {}
  41. item_ids = []
  42. users.each do |item|
  43. item_ids.push item.id
  44. assets = item.assets(assets)
  45. end
  46. render json: {
  47. record_ids: item_ids,
  48. assets: assets,
  49. }, status: :ok
  50. return
  51. end
  52. users_all = []
  53. users.each do |user|
  54. users_all.push User.lookup(id: user.id).attributes_with_association_ids
  55. end
  56. render json: users_all, status: :ok
  57. end
  58. # @path [GET] /users/{id}
  59. #
  60. # @summary Returns the User record with the requested identifier.
  61. # @notes The requester has to be in the role 'Admin' or 'Agent' to
  62. # access all User records. If the requester is in the
  63. # role 'Customer' just the own User record is accessable.
  64. #
  65. # @parameter id(required) [Integer] The identifier matching the requested User.
  66. # @parameter full [Bool] If set a Asset structure with all connected Assets gets returned.
  67. #
  68. # @response_message 200 [User] User record matching the requested identifier.
  69. # @response_message 401 Invalid session.
  70. def show
  71. user = User.find(params[:id])
  72. access!(user, 'read')
  73. if response_expand?
  74. result = user.attributes_with_association_names
  75. result.delete('password')
  76. render json: result
  77. return
  78. end
  79. if response_full?
  80. result = {
  81. id: user.id,
  82. assets: user.assets({}),
  83. }
  84. render json: result
  85. return
  86. end
  87. result = user.attributes_with_association_ids
  88. result.delete('password')
  89. render json: result
  90. end
  91. # @path [POST] /users
  92. #
  93. # @summary Creates a User record with the provided attribute values.
  94. # @notes TODO.
  95. #
  96. # @parameter User(required,body) [User] The attribute value structure needed to create a User record.
  97. #
  98. # @response_message 200 [User] Created User record.
  99. # @response_message 401 Invalid session.
  100. def create
  101. clean_params = User.association_name_to_id_convert(params)
  102. clean_params = User.param_cleanup(clean_params, true)
  103. # check if it's first user, the admin user
  104. # inital admin account
  105. count = User.all.count
  106. admin_account_exists = true
  107. if count <= 2
  108. admin_account_exists = false
  109. end
  110. # if it's a signup, add user to customer role
  111. if !current_user
  112. # check if feature is enabled
  113. if admin_account_exists && !Setting.get('user_create_account')
  114. raise Exceptions::UnprocessableEntity, 'Feature not enabled!'
  115. end
  116. # check signup option only after admin account is created
  117. if admin_account_exists && !params[:signup]
  118. raise Exceptions::UnprocessableEntity, 'Only signup with not authenticate user possible!'
  119. end
  120. # check if user already exists
  121. if clean_params[:email].blank?
  122. raise Exceptions::UnprocessableEntity, 'Attribute \'email\' required!'
  123. end
  124. # check if user already exists
  125. exists = User.find_by(email: clean_params[:email].downcase.strip)
  126. raise Exceptions::UnprocessableEntity, 'Email address is already used for other user.' if exists
  127. user = User.new(clean_params)
  128. user.associations_from_param(params)
  129. user.updated_by_id = 1
  130. user.created_by_id = 1
  131. # add first user as admin/agent and to all groups
  132. group_ids = []
  133. role_ids = []
  134. if count <= 2
  135. Role.where(name: %w[Admin Agent]).each do |role|
  136. role_ids.push role.id
  137. end
  138. Group.all.each do |group|
  139. group_ids.push group.id
  140. end
  141. # everybody else will go as customer per default
  142. else
  143. role_ids = Role.signup_role_ids
  144. end
  145. user.role_ids = role_ids
  146. user.group_ids = group_ids
  147. # remember source (in case show email verify banner)
  148. # if not inital user creation
  149. if admin_account_exists
  150. user.source = 'signup'
  151. end
  152. # else do assignment as defined
  153. else
  154. # permission check
  155. check_attributes_by_current_user_permission(params)
  156. user = User.new(clean_params)
  157. user.associations_from_param(params)
  158. end
  159. user.save!
  160. # if first user was added, set system init done
  161. if !admin_account_exists
  162. Setting.set('system_init_done', true)
  163. # fetch org logo
  164. if user.email.present?
  165. Service::Image.organization_suggest(user.email)
  166. end
  167. # load calendar
  168. Calendar.init_setup(request.remote_ip)
  169. # load text modules
  170. begin
  171. TextModule.load(request.env['HTTP_ACCEPT_LANGUAGE'] || 'en-us')
  172. rescue => e
  173. logger.error "Unable to load text modules #{request.env['HTTP_ACCEPT_LANGUAGE'] || 'en-us'}: #{e.message}"
  174. end
  175. end
  176. # send inviteation if needed / only if session exists
  177. if params[:invite].present? && current_user
  178. sleep 5 if ENV['REMOTE_URL'].present?
  179. token = Token.create(action: 'PasswordReset', user_id: user.id)
  180. NotificationFactory::Mailer.notification(
  181. template: 'user_invite',
  182. user: user,
  183. objects: {
  184. token: token,
  185. user: user,
  186. current_user: current_user,
  187. }
  188. )
  189. end
  190. # send email verify
  191. if params[:signup].present? && !current_user
  192. result = User.signup_new_token(user)
  193. NotificationFactory::Mailer.notification(
  194. template: 'signup',
  195. user: user,
  196. objects: result,
  197. )
  198. end
  199. if response_expand?
  200. user = user.reload.attributes_with_association_names
  201. user.delete('password')
  202. render json: user, status: :created
  203. return
  204. end
  205. if response_full?
  206. result = {
  207. id: user.id,
  208. assets: user.assets({}),
  209. }
  210. render json: result, status: :created
  211. return
  212. end
  213. user = user.reload.attributes_with_association_ids
  214. user.delete('password')
  215. render json: user, status: :created
  216. end
  217. # @path [PUT] /users/{id}
  218. #
  219. # @summary Updates the User record matching the identifier with the provided attribute values.
  220. # @notes TODO.
  221. #
  222. # @parameter id(required) [Integer] The identifier matching the requested User record.
  223. # @parameter User(required,body) [User] The attribute value structure needed to update a User record.
  224. #
  225. # @response_message 200 [User] Updated User record.
  226. # @response_message 401 Invalid session.
  227. def update
  228. user = User.find(params[:id])
  229. access!(user, 'change')
  230. # permission check
  231. check_attributes_by_current_user_permission(params)
  232. user.with_lock do
  233. clean_params = User.association_name_to_id_convert(params)
  234. clean_params = User.param_cleanup(clean_params, true)
  235. user.update!(clean_params)
  236. # presence and permissions were checked via `check_attributes_by_current_user_permission`
  237. privileged_attributes = params.slice(:role_ids, :roles, :group_ids, :groups, :organization_ids, :organizations)
  238. if privileged_attributes.present?
  239. user.associations_from_param(privileged_attributes)
  240. end
  241. end
  242. if response_expand?
  243. user = user.reload.attributes_with_association_names
  244. user.delete('password')
  245. render json: user, status: :ok
  246. return
  247. end
  248. if response_full?
  249. result = {
  250. id: user.id,
  251. assets: user.assets({}),
  252. }
  253. render json: result, status: :ok
  254. return
  255. end
  256. user = user.reload.attributes_with_association_ids
  257. user.delete('password')
  258. render json: user, status: :ok
  259. end
  260. # @path [DELETE] /users/{id}
  261. #
  262. # @summary Deletes the User record matching the given identifier.
  263. # @notes The requester has to be in the role 'Admin' to be able to delete a User record.
  264. #
  265. # @parameter id(required) [User] The identifier matching the requested User record.
  266. #
  267. # @response_message 200 User successfully deleted.
  268. # @response_message 401 Invalid session.
  269. def destroy
  270. user = User.find(params[:id])
  271. access!(user, 'delete')
  272. model_references_check(User, params)
  273. model_destroy_render(User, params)
  274. end
  275. # @path [GET] /users/me
  276. #
  277. # @summary Returns the User record of current user.
  278. # @notes The requestor need to have a valid authentication.
  279. #
  280. # @parameter full [Bool] If set a Asset structure with all connected Assets gets returned.
  281. #
  282. # @response_message 200 [User] User record matching the requested identifier.
  283. # @response_message 401 Invalid session.
  284. def me
  285. if response_expand?
  286. user = current_user.attributes_with_association_names
  287. user.delete('password')
  288. render json: user, status: :ok
  289. return
  290. end
  291. if response_full?
  292. full = User.full(current_user.id)
  293. render json: full
  294. return
  295. end
  296. user = current_user.attributes_with_association_ids
  297. user.delete('password')
  298. render json: user
  299. end
  300. # @path [GET] /users/search
  301. #
  302. # @tag Search
  303. # @tag User
  304. #
  305. # @summary Searches the User matching the given expression(s).
  306. # @notes TODO: It's possible to use the SOLR search syntax.
  307. # The requester has to be in the role 'Admin' or 'Agent' to
  308. # be able to search for User records.
  309. #
  310. # @parameter query [String] The search query.
  311. # @parameter limit [Integer] The limit of search results.
  312. # @parameter role_ids(multi) [Array<String>] A list of Role identifiers to which the Users have to be allocated to.
  313. # @parameter full [Boolean] Defines if the result should be
  314. # true: { user_ids => [1,2,...], assets => {...} }
  315. # or false: [{:id => user.id, :label => "firstname lastname <email>", :value => "firstname lastname <email>"},...].
  316. #
  317. # @response_message 200 [Array<User>] A list of User records matching the search term.
  318. # @response_message 401 Invalid session.
  319. def search
  320. if !current_user.permissions?(['ticket.agent', 'admin.user'])
  321. response_access_deny
  322. return
  323. end
  324. # set limit for pagination if needed
  325. if params[:page] && params[:per_page]
  326. params[:limit] = params[:page].to_i * params[:per_page].to_i
  327. end
  328. if params[:limit] && params[:limit].to_i > 500
  329. params[:limit] = 500
  330. end
  331. query = params[:query] || params[:term]
  332. if query.respond_to?(:permit!)
  333. query = query.permit!.to_h
  334. end
  335. query_params = {
  336. query: query,
  337. limit: params[:limit],
  338. current_user: current_user,
  339. }
  340. %i[role_ids permissions].each do |key|
  341. next if params[key].blank?
  342. query_params[key] = params[key]
  343. end
  344. # do query
  345. user_all = User.search(query_params)
  346. # do pagination if needed
  347. if params[:page] && params[:per_page]
  348. offset = (params[:page].to_i - 1) * params[:per_page].to_i
  349. user_all = user_all[offset, params[:per_page].to_i] || []
  350. end
  351. if response_expand?
  352. list = []
  353. user_all.each do |user|
  354. list.push user.attributes_with_association_names
  355. end
  356. render json: list, status: :ok
  357. return
  358. end
  359. # build result list
  360. if params[:label] || params[:term]
  361. users = []
  362. user_all.each do |user|
  363. realname = user.fullname
  364. if user.email.present? && realname != user.email
  365. realname = "#{realname} <#{user.email}>"
  366. end
  367. a = if params[:term]
  368. { id: user.id, label: realname, value: user.email }
  369. else
  370. { id: user.id, label: realname, value: realname }
  371. end
  372. users.push a
  373. end
  374. # return result
  375. render json: users
  376. return
  377. end
  378. if response_full?
  379. user_ids = []
  380. assets = {}
  381. user_all.each do |user|
  382. assets = user.assets(assets)
  383. user_ids.push user.id
  384. end
  385. # return result
  386. render json: {
  387. assets: assets,
  388. user_ids: user_ids.uniq,
  389. }
  390. return
  391. end
  392. list = []
  393. user_all.each do |user|
  394. list.push user.attributes_with_association_ids
  395. end
  396. render json: list, status: :ok
  397. end
  398. # @path [GET] /users/recent
  399. #
  400. # @tag Search
  401. # @tag User
  402. #
  403. # @summary Recent creates Users.
  404. # @notes Recent creates Users.
  405. #
  406. # @parameter limit [Integer] The limit of search results.
  407. # @parameter role_ids(multi) [Array<String>] A list of Role identifiers to which the Users have to be allocated to.
  408. # @parameter full [Boolean] Defines if the result should be
  409. # true: { user_ids => [1,2,...], assets => {...} }
  410. # or false: [{:id => user.id, :label => "firstname lastname <email>", :value => "firstname lastname <email>"},...].
  411. #
  412. # @response_message 200 [Array<User>] A list of User records matching the search term.
  413. # @response_message 401 Invalid session.
  414. def recent
  415. if !current_user.permissions?('admin.user')
  416. response_access_deny
  417. return
  418. end
  419. # do query
  420. user_all = if params[:role_ids].present?
  421. User.joins(:roles).where('roles.id' => params[:role_ids]).where('users.id != 1').order('users.created_at DESC').limit(params[:limit] || 20)
  422. else
  423. User.where('id != 1').order('created_at DESC').limit(params[:limit] || 20)
  424. end
  425. # build result list
  426. if !response_full?
  427. users = []
  428. user_all.each do |user|
  429. realname = user.firstname.to_s + ' ' + user.lastname.to_s
  430. if user.email && user.email.to_s != ''
  431. realname = realname + ' <' + user.email.to_s + '>'
  432. end
  433. a = { id: user.id, label: realname, value: realname }
  434. users.push a
  435. end
  436. # return result
  437. render json: users
  438. return
  439. end
  440. user_ids = []
  441. assets = {}
  442. user_all.each do |user|
  443. assets = user.assets(assets)
  444. user_ids.push user.id
  445. end
  446. # return result
  447. render json: {
  448. assets: assets,
  449. user_ids: user_ids.uniq,
  450. }
  451. end
  452. # @path [GET] /users/history/{id}
  453. #
  454. # @tag History
  455. # @tag User
  456. #
  457. # @summary Returns the History records of a User record matching the given identifier.
  458. # @notes The requester has to be in the role 'Admin' or 'Agent' to
  459. # get the History records of a User record.
  460. #
  461. # @parameter id(required) [Integer] The identifier matching the requested User record.
  462. #
  463. # @response_message 200 [History] The History records of the requested User record.
  464. # @response_message 401 Invalid session.
  465. def history
  466. # permission check
  467. if !current_user.permissions?(['admin.user', 'ticket.agent'])
  468. response_access_deny
  469. return
  470. end
  471. # get user data
  472. user = User.find(params[:id])
  473. # get history of user
  474. history = user.history_get(true)
  475. # return result
  476. render json: history
  477. end
  478. =begin
  479. Resource:
  480. POST /api/v1/users/email_verify
  481. Payload:
  482. {
  483. "token": "SoMeToKeN",
  484. }
  485. Response:
  486. {
  487. :message => 'ok'
  488. }
  489. Test:
  490. curl http://localhost/api/v1/users/email_verify -v -u #{login}:#{password} -H "Content-Type: application/json" -X POST -d '{"token": "SoMeToKeN"}'
  491. =end
  492. def email_verify
  493. raise Exceptions::UnprocessableEntity, 'No token!' if !params[:token]
  494. user = User.signup_verify_via_token(params[:token], current_user)
  495. raise Exceptions::UnprocessableEntity, 'Invalid token!' if !user
  496. render json: { message: 'ok', user_email: user.email }, status: :ok
  497. end
  498. =begin
  499. Resource:
  500. POST /api/v1/users/email_verify_send
  501. Payload:
  502. {
  503. "email": "some_email@example.com"
  504. }
  505. Response:
  506. {
  507. :message => 'ok'
  508. }
  509. Test:
  510. curl http://localhost/api/v1/users/email_verify_send -v -u #{login}:#{password} -H "Content-Type: application/json" -X POST -d '{"email": "some_email@example.com"}'
  511. =end
  512. def email_verify_send
  513. raise Exceptions::UnprocessableEntity, 'No email!' if !params[:email]
  514. # check is verify is possible to send
  515. user = User.find_by(email: params[:email].downcase)
  516. raise Exceptions::UnprocessableEntity, 'No such user!' if !user
  517. #if user.verified == true
  518. # render json: { error: 'Already verified!' }, status: :unprocessable_entity
  519. # return
  520. #end
  521. token = Token.create(action: 'Signup', user_id: user.id)
  522. result = User.signup_new_token(user)
  523. if result && result[:token]
  524. user = result[:user]
  525. NotificationFactory::Mailer.notification(
  526. template: 'signup',
  527. user: user,
  528. objects: result
  529. )
  530. # only if system is in develop mode, send token back to browser for browser tests
  531. if Setting.get('developer_mode') == true
  532. render json: { message: 'ok', token: result[:token].name }, status: :ok
  533. return
  534. end
  535. # token sent to user, send ok to browser
  536. render json: { message: 'ok' }, status: :ok
  537. return
  538. end
  539. # unable to generate token
  540. render json: { message: 'failed' }, status: :ok
  541. end
  542. =begin
  543. Resource:
  544. POST /api/v1/users/password_reset
  545. Payload:
  546. {
  547. "username": "some user name"
  548. }
  549. Response:
  550. {
  551. :message => 'ok'
  552. }
  553. Test:
  554. curl http://localhost/api/v1/users/password_reset -v -u #{login}:#{password} -H "Content-Type: application/json" -X POST -d '{"username": "some_username"}'
  555. =end
  556. def password_reset_send
  557. # check if feature is enabled
  558. raise Exceptions::UnprocessableEntity, 'Feature not enabled!' if !Setting.get('user_lost_password')
  559. result = User.password_reset_new_token(params[:username])
  560. if result && result[:token]
  561. # send mail
  562. user = result[:user]
  563. NotificationFactory::Mailer.notification(
  564. template: 'password_reset',
  565. user: user,
  566. objects: result
  567. )
  568. # only if system is in develop mode, send token back to browser for browser tests
  569. if Setting.get('developer_mode') == true
  570. render json: { message: 'ok', token: result[:token].name }, status: :ok
  571. return
  572. end
  573. # token sent to user, send ok to browser
  574. render json: { message: 'ok' }, status: :ok
  575. return
  576. end
  577. # unable to generate token
  578. render json: { message: 'failed' }, status: :ok
  579. end
  580. =begin
  581. Resource:
  582. POST /api/v1/users/password_reset_verify
  583. Payload:
  584. {
  585. "token": "SoMeToKeN",
  586. "password": "new_password"
  587. }
  588. Response:
  589. {
  590. :message => 'ok'
  591. }
  592. Test:
  593. curl http://localhost/api/v1/users/password_reset_verify -v -u #{login}:#{password} -H "Content-Type: application/json" -X POST -d '{"token": "SoMeToKeN", "password" "new_password"}'
  594. =end
  595. def password_reset_verify
  596. if params[:password]
  597. # check password policy
  598. result = password_policy(params[:password])
  599. if result != true
  600. render json: { message: 'failed', notice: result }, status: :ok
  601. return
  602. end
  603. # set new password with token
  604. user = User.password_reset_via_token(params[:token], params[:password])
  605. # send mail
  606. if user
  607. NotificationFactory::Mailer.notification(
  608. template: 'password_change',
  609. user: user,
  610. objects: {
  611. user: user,
  612. current_user: current_user,
  613. }
  614. )
  615. end
  616. else
  617. user = User.by_reset_token(params[:token])
  618. end
  619. if user
  620. render json: { message: 'ok', user_login: user.login }, status: :ok
  621. else
  622. render json: { message: 'failed' }, status: :ok
  623. end
  624. end
  625. =begin
  626. Resource:
  627. POST /api/v1/users/password_change
  628. Payload:
  629. {
  630. "password_old": "some_password_old",
  631. "password_new": "some_password_new"
  632. }
  633. Response:
  634. {
  635. :message => 'ok'
  636. }
  637. Test:
  638. curl http://localhost/api/v1/users/password_change -v -u #{login}:#{password} -H "Content-Type: application/json" -X POST -d '{"password_old": "password_old", "password_new": "password_new"}'
  639. =end
  640. def password_change
  641. # check old password
  642. if !params[:password_old]
  643. render json: { message: 'failed', notice: ['Current password needed!'] }, status: :ok
  644. return
  645. end
  646. user = User.authenticate(current_user.login, params[:password_old])
  647. if !user
  648. render json: { message: 'failed', notice: ['Current password is wrong!'] }, status: :ok
  649. return
  650. end
  651. # set new password
  652. if !params[:password_new]
  653. render json: { message: 'failed', notice: ['Please supply your new password!'] }, status: :ok
  654. return
  655. end
  656. # check password policy
  657. result = password_policy(params[:password_new])
  658. if result != true
  659. render json: { message: 'failed', notice: result }, status: :ok
  660. return
  661. end
  662. user.update!(password: params[:password_new])
  663. NotificationFactory::Mailer.notification(
  664. template: 'password_change',
  665. user: user,
  666. objects: {
  667. user: user,
  668. current_user: current_user,
  669. }
  670. )
  671. render json: { message: 'ok', user_login: user.login }, status: :ok
  672. end
  673. =begin
  674. Resource:
  675. PUT /api/v1/users/preferences
  676. Payload:
  677. {
  678. "language": "de",
  679. "notification": true
  680. }
  681. Response:
  682. {
  683. :message => 'ok'
  684. }
  685. Test:
  686. curl http://localhost/api/v1/users/preferences -v -u #{login}:#{password} -H "Content-Type: application/json" -X PUT -d '{"language": "de", "notifications": true}'
  687. =end
  688. def preferences
  689. raise Exceptions::UnprocessableEntity, 'No current user!' if !current_user
  690. preferences_params = params.except(:controller, :action)
  691. if preferences_params.present?
  692. user = User.find(current_user.id)
  693. user.with_lock do
  694. preferences_params.permit!.to_h.each do |key, value|
  695. user.preferences[key.to_sym] = value
  696. end
  697. user.save!
  698. end
  699. end
  700. render json: { message: 'ok' }, status: :ok
  701. end
  702. =begin
  703. Resource:
  704. PUT /api/v1/users/out_of_office
  705. Payload:
  706. {
  707. "out_of_office": true,
  708. "out_of_office_start_at": true,
  709. "out_of_office_end_at": true,
  710. "out_of_office_replacement_id": 123,
  711. "out_of_office_text": 'honeymoon'
  712. }
  713. Response:
  714. {
  715. :message => 'ok'
  716. }
  717. Test:
  718. curl http://localhost/api/v1/users/out_of_office -v -u #{login}:#{password} -H "Content-Type: application/json" -X PUT -d '{"out_of_office": true, "out_of_office_replacement_id": 123}'
  719. =end
  720. def out_of_office
  721. raise Exceptions::UnprocessableEntity, 'No current user!' if !current_user
  722. user = User.find(current_user.id)
  723. user.with_lock do
  724. user.assign_attributes(
  725. out_of_office: params[:out_of_office],
  726. out_of_office_start_at: params[:out_of_office_start_at],
  727. out_of_office_end_at: params[:out_of_office_end_at],
  728. out_of_office_replacement_id: params[:out_of_office_replacement_id],
  729. )
  730. user.preferences[:out_of_office_text] = params[:out_of_office_text]
  731. user.save!
  732. end
  733. render json: { message: 'ok' }, status: :ok
  734. end
  735. =begin
  736. Resource:
  737. DELETE /api/v1/users/account
  738. Payload:
  739. {
  740. "provider": "twitter",
  741. "uid": 581482342942
  742. }
  743. Response:
  744. {
  745. :message => 'ok'
  746. }
  747. Test:
  748. curl http://localhost/api/v1/users/account -v -u #{login}:#{password} -H "Content-Type: application/json" -X PUT -d '{"provider": "twitter", "uid": 581482342942}'
  749. =end
  750. def account_remove
  751. raise Exceptions::UnprocessableEntity, 'No current user!' if !current_user
  752. # provider + uid to remove
  753. raise Exceptions::UnprocessableEntity, 'provider needed!' if !params[:provider]
  754. raise Exceptions::UnprocessableEntity, 'uid needed!' if !params[:uid]
  755. # remove from database
  756. record = Authorization.where(
  757. user_id: current_user.id,
  758. provider: params[:provider],
  759. uid: params[:uid],
  760. )
  761. raise Exceptions::UnprocessableEntity, 'No record found!' if !record.first
  762. record.destroy_all
  763. render json: { message: 'ok' }, status: :ok
  764. end
  765. =begin
  766. Resource:
  767. GET /api/v1/users/image/8d6cca1c6bdc226cf2ba131e264ca2c7
  768. Response:
  769. <IMAGE>
  770. Test:
  771. curl http://localhost/api/v1/users/image/8d6cca1c6bdc226cf2ba131e264ca2c7 -v -u #{login}:#{password}
  772. =end
  773. def image
  774. # cache image
  775. response.headers['Expires'] = 1.year.from_now.httpdate
  776. response.headers['Cache-Control'] = 'cache, store, max-age=31536000, must-revalidate'
  777. response.headers['Pragma'] = 'cache'
  778. file = Avatar.get_by_hash(params[:hash])
  779. if file
  780. send_data(
  781. file.content,
  782. filename: file.filename,
  783. type: file.preferences['Content-Type'] || file.preferences['Mime-Type'],
  784. disposition: 'inline'
  785. )
  786. return
  787. end
  788. # serve default image
  789. image = 'R0lGODdhMAAwAOMAAMzMzJaWlr6+vqqqqqOjo8XFxbe3t7GxsZycnAAAAAAAAAAAAAAAAAAAAAAAAAAAACwAAAAAMAAwAAAEcxDISau9OOvNu/9gKI5kaZ5oqq5s675wLM90bd94ru98TwuAA+KQAQqJK8EAgBAgMEqmkzUgBIeSwWGZtR5XhSqAULACCoGCJGwlm1MGQrq9RqgB8fm4ZTUgDBIEcRR9fz6HiImKi4yNjo+QkZKTlJWWkBEAOw=='
  790. send_data(
  791. Base64.decode64(image),
  792. filename: 'image.gif',
  793. type: 'image/gif',
  794. disposition: 'inline'
  795. )
  796. end
  797. =begin
  798. Resource:
  799. POST /api/v1/users/avatar
  800. Payload:
  801. {
  802. "avatar_full": "base64 url",
  803. }
  804. Response:
  805. {
  806. message: 'ok'
  807. }
  808. Test:
  809. curl http://localhost/api/v1/users/avatar -v -u #{login}:#{password} -H "Content-Type: application/json" -X POST -d '{"avatar": "base64 url"}'
  810. =end
  811. def avatar_new
  812. return if !valid_session_with_user
  813. # get & validate image
  814. file_full = StaticAssets.data_url_attributes(params[:avatar_full])
  815. file_resize = StaticAssets.data_url_attributes(params[:avatar_resize])
  816. avatar = Avatar.add(
  817. object: 'User',
  818. o_id: current_user.id,
  819. full: {
  820. content: file_full[:content],
  821. mime_type: file_full[:mime_type],
  822. },
  823. resize: {
  824. content: file_resize[:content],
  825. mime_type: file_resize[:mime_type],
  826. },
  827. source: 'upload ' + Time.zone.now.to_s,
  828. deletable: true,
  829. )
  830. # update user link
  831. user = User.find(current_user.id)
  832. user.update!(image: avatar.store_hash)
  833. render json: { avatar: avatar }, status: :ok
  834. end
  835. def avatar_set_default
  836. return if !valid_session_with_user
  837. # get & validate image
  838. raise Exceptions::UnprocessableEntity, 'No id of avatar!' if !params[:id]
  839. # set as default
  840. avatar = Avatar.set_default('User', current_user.id, params[:id])
  841. # update user link
  842. user = User.find(current_user.id)
  843. user.update!(image: avatar.store_hash)
  844. render json: {}, status: :ok
  845. end
  846. def avatar_destroy
  847. return if !valid_session_with_user
  848. # get & validate image
  849. raise Exceptions::UnprocessableEntity, 'No id of avatar!' if !params[:id]
  850. # remove avatar
  851. Avatar.remove_one('User', current_user.id, params[:id])
  852. # update user link
  853. avatar = Avatar.get_default('User', current_user.id)
  854. user = User.find(current_user.id)
  855. user.update!(image: avatar.store_hash)
  856. render json: {}, status: :ok
  857. end
  858. def avatar_list
  859. return if !valid_session_with_user
  860. # list of avatars
  861. result = Avatar.list('User', current_user.id)
  862. render json: { avatars: result }, status: :ok
  863. end
  864. # @path [GET] /users/import_example
  865. #
  866. # @summary Download of example CSV file.
  867. # @notes The requester have 'admin.user' permissions to be able to download it.
  868. # @example curl -u 'me@example.com:test' http://localhost:3000/api/v1/users/import_example
  869. #
  870. # @response_message 200 File download.
  871. # @response_message 401 Invalid session.
  872. def import_example
  873. permission_check('admin.user')
  874. send_data(
  875. User.csv_example,
  876. filename: 'user-example.csv',
  877. type: 'text/csv',
  878. disposition: 'attachment'
  879. )
  880. end
  881. # @path [POST] /users/import
  882. #
  883. # @summary Starts import.
  884. # @notes The requester have 'admin.text_module' permissions to be create a new import.
  885. # @example curl -u 'me@example.com:test' -F 'file=@/path/to/file/users.csv' 'https://your.zammad/api/v1/users/import?try=true'
  886. # @example curl -u 'me@example.com:test' -F 'file=@/path/to/file/users.csv' 'https://your.zammad/api/v1/users/import'
  887. #
  888. # @response_message 201 Import started.
  889. # @response_message 401 Invalid session.
  890. def import_start
  891. permission_check('admin.user')
  892. result = User.csv_import(
  893. string: params[:file].read.force_encoding('utf-8'),
  894. parse_params: {
  895. col_sep: ';',
  896. },
  897. try: params[:try],
  898. )
  899. render json: result, status: :ok
  900. end
  901. private
  902. def password_policy(password)
  903. if Setting.get('password_min_size').to_i > password.length
  904. return ["Can\'t update password, it must be at least %s characters long!", Setting.get('password_min_size')]
  905. end
  906. if Setting.get('password_need_digit').to_i == 1 && password !~ /\d/
  907. return ["Can't update password, it must contain at least 1 digit!"]
  908. end
  909. if Setting.get('password_min_2_lower_2_upper_characters').to_i == 1 && ( password !~ /[A-Z].*[A-Z]/ || password !~ /[a-z].*[a-z]/ )
  910. return ["Can't update password, it must contain at least 2 lowercase and 2 uppercase characters!"]
  911. end
  912. true
  913. end
  914. end