users_controller.rb 30 KB

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