users_controller.rb 30 KB

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