users_controller.rb 32 KB

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