users_controller.rb 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064
  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 = []
  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. # presence and permissions were checked via `check_attributes_by_current_user_permission`
  112. privileged_attributes = params.slice(:role_ids, :roles, :group_ids, :groups, :organization_ids, :organizations)
  113. if privileged_attributes.present?
  114. user.associations_from_param(privileged_attributes)
  115. end
  116. user.update!(clean_params)
  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. verify = Service::User::SignupVerify.new(token: params[:token], current_user: current_user)
  320. begin
  321. user = verify.execute
  322. rescue Service::CheckFeatureEnabled::FeatureDisabledError, Service::User::SignupVerify::InvalidTokenError => e
  323. raise Exceptions::UnprocessableEntity, e.message
  324. end
  325. current_user_set(user) if user
  326. msg = user ? { message: 'ok', user_email: user.email } : { message: 'failed' }
  327. render json: msg, status: :ok
  328. end
  329. =begin
  330. Resource:
  331. POST /api/v1/users/email_verify_send
  332. Payload:
  333. {
  334. "email": "some_email@example.com"
  335. }
  336. Response:
  337. {
  338. :message => 'ok'
  339. }
  340. Test:
  341. 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"}'
  342. =end
  343. def email_verify_send
  344. raise Exceptions::UnprocessableEntity, __('No email!') if !params[:email]
  345. signup = Service::User::Deprecated::Signup.new(user_data: { email: params[:email] }, resend: true)
  346. begin
  347. signup.execute
  348. rescue Service::CheckFeatureEnabled::FeatureDisabledError => e
  349. raise Exceptions::UnprocessableEntity, e.message
  350. rescue Service::User::Signup::TokenGenerationError
  351. render json: { message: 'failed' }, status: :ok
  352. end
  353. # Result is always positive to avoid leaking of existing user accounts.
  354. render json: { message: 'ok' }, status: :ok
  355. end
  356. =begin
  357. Resource:
  358. POST /api/v1/users/admin_login
  359. Payload:
  360. {
  361. "username": "some user name"
  362. }
  363. Response:
  364. {
  365. :message => 'ok'
  366. }
  367. Test:
  368. curl http://localhost/api/v1/users/admin_login -v -u #{login}:#{password} -H "Content-Type: application/json" -X POST -d '{"username": "some_username"}'
  369. =end
  370. def admin_password_auth_send
  371. raise Exceptions::UnprocessableEntity, 'username param needed!' if params[:username].blank?
  372. send = Service::Auth::Deprecated::SendAdminToken.new(login: params[:username])
  373. begin
  374. send.execute
  375. rescue Service::CheckFeatureEnabled::FeatureDisabledError => e
  376. raise Exceptions::UnprocessableEntity, e.message
  377. rescue Service::Auth::Deprecated::SendAdminToken::TokenError, Service::Auth::Deprecated::SendAdminToken::EmailError
  378. render json: { message: 'failed' }, status: :ok
  379. return
  380. end
  381. render json: { message: 'ok' }, status: :ok
  382. end
  383. def admin_password_auth_verify
  384. raise Exceptions::UnprocessableEntity, 'token param needed!' if params[:token].blank?
  385. verify = Service::Auth::VerifyAdminToken.new(token: params[:token])
  386. user = begin
  387. verify.execute
  388. rescue => e
  389. raise Exceptions::UnprocessableEntity, e.message
  390. end
  391. msg = user ? { message: 'ok', user_login: user.login } : { message: 'failed' }
  392. render json: msg, status: :ok
  393. end
  394. =begin
  395. Resource:
  396. POST /api/v1/users/password_reset
  397. Payload:
  398. {
  399. "username": "some user name"
  400. }
  401. Response:
  402. {
  403. :message => 'ok'
  404. }
  405. Test:
  406. curl http://localhost/api/v1/users/password_reset -v -u #{login}:#{password} -H "Content-Type: application/json" -X POST -d '{"username": "some_username"}'
  407. =end
  408. def password_reset_send
  409. raise Exceptions::UnprocessableEntity, 'username param needed!' if params[:username].blank?
  410. send = Service::User::PasswordReset::Deprecated::Send.new(username: params[:username])
  411. begin
  412. send.execute
  413. rescue Service::CheckFeatureEnabled::FeatureDisabledError => e
  414. raise Exceptions::UnprocessableEntity, e.message
  415. rescue Service::User::PasswordReset::Send::EmailError
  416. render json: { message: 'failed' }, status: :ok
  417. return
  418. end
  419. # Result is always positive to avoid leaking of existing user accounts.
  420. render json: { message: 'ok' }, status: :ok
  421. end
  422. =begin
  423. Resource:
  424. POST /api/v1/users/password_reset_verify
  425. Payload:
  426. {
  427. "token": "SoMeToKeN",
  428. "password": "new_pw"
  429. }
  430. Response:
  431. {
  432. :message => 'ok'
  433. }
  434. Test:
  435. 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"}'
  436. =end
  437. def password_reset_verify
  438. raise Exceptions::UnprocessableEntity, 'token param needed!' if params[:token].blank?
  439. # If no password is given, verify token only.
  440. if params[:password].blank?
  441. verify = Service::User::PasswordReset::Verify.new(token: params[:token])
  442. begin
  443. user = verify.execute
  444. rescue Service::CheckFeatureEnabled::FeatureDisabledError => e
  445. raise Exceptions::UnprocessableEntity, e.message
  446. rescue Service::User::PasswordReset::Verify::InvalidTokenError
  447. render json: { message: 'failed' }, status: :ok
  448. return
  449. end
  450. render json: { message: 'ok', user_login: user.login }, status: :ok
  451. return
  452. end
  453. update = Service::User::PasswordReset::Update.new(token: params[:token], password: params[:password])
  454. begin
  455. user = update.execute
  456. rescue Service::CheckFeatureEnabled::FeatureDisabledError => e
  457. raise Exceptions::UnprocessableEntity, e.message
  458. rescue Service::User::PasswordReset::Update::InvalidTokenError, Service::User::PasswordReset::Update::EmailError
  459. render json: { message: 'failed' }, status: :ok
  460. return
  461. rescue PasswordPolicy::Error => e
  462. render json: { message: 'failed', notice: [e] }, status: :ok
  463. return
  464. end
  465. render json: { message: 'ok', user_login: user.login }, status: :ok
  466. end
  467. =begin
  468. Resource:
  469. POST /api/v1/users/password_change
  470. Payload:
  471. {
  472. "password_old": "old_pw",
  473. "password_new": "new_pw"
  474. }
  475. Response:
  476. {
  477. :message => 'ok'
  478. }
  479. Test:
  480. 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"}'
  481. =end
  482. def password_change
  483. # check old password
  484. if !params[:password_old] || !PasswordPolicy::MaxLength.valid?(params[:password_old])
  485. render json: { message: 'failed', notice: [__('Please provide your current password.')] }, status: :unprocessable_entity
  486. return
  487. end
  488. current_password_verified = PasswordHash.verified?(current_user.password, params[:password_old])
  489. if !current_password_verified
  490. render json: { message: 'failed', notice: [__('The current password you provided is incorrect.')] }, status: :unprocessable_entity
  491. return
  492. end
  493. # set new password
  494. if !params[:password_new]
  495. render json: { message: 'failed', notice: [__('Please provide your new password.')] }, status: :unprocessable_entity
  496. return
  497. end
  498. result = PasswordPolicy.new(params[:password_new])
  499. if !result.valid?
  500. render json: { message: 'failed', notice: result.error }, status: :unprocessable_entity
  501. return
  502. end
  503. current_user.update!(password: params[:password_new])
  504. if current_user.email.present?
  505. NotificationFactory::Mailer.notification(
  506. template: 'password_change',
  507. user: current_user,
  508. objects: {
  509. user: current_user,
  510. }
  511. )
  512. end
  513. render json: { message: 'ok', user_login: current_user.login }, status: :ok
  514. end
  515. def password_check
  516. raise Exceptions::UnprocessableEntity, __("The required parameter 'password' is missing.") if params[:password].blank?
  517. begin
  518. Auth.new(current_user.login, params[:password], only_verify_password: true).valid!
  519. render json: { success: true }, status: :ok
  520. rescue Auth::Error::AuthenticationFailed
  521. render json: { success: false }, status: :ok
  522. end
  523. end
  524. =begin
  525. Resource:
  526. PUT /api/v1/users/preferences
  527. Payload:
  528. {
  529. "language": "de",
  530. "notification": true
  531. }
  532. Response:
  533. {
  534. :message => 'ok'
  535. }
  536. Test:
  537. curl http://localhost/api/v1/users/preferences -v -u #{login}:#{password} -H "Content-Type: application/json" -X PUT -d '{"language": "de", "notifications": true}'
  538. =end
  539. def preferences
  540. preferences_params = params.except(:controller, :action)
  541. if preferences_params.present?
  542. user = User.find(current_user.id)
  543. user.with_lock do
  544. preferences_params.permit!.to_h.each do |key, value|
  545. user.preferences[key.to_sym] = value
  546. end
  547. user.save!
  548. end
  549. end
  550. render json: { message: 'ok' }, status: :ok
  551. end
  552. =begin
  553. Resource:
  554. POST /api/v1/users/preferences_reset
  555. Response:
  556. {
  557. :message => 'ok'
  558. }
  559. Test:
  560. curl http://localhost/api/v1/users/preferences_reset -v -u #{login}:#{password} -H "Content-Type: application/json" -X POST'
  561. =end
  562. def preferences_notifications_reset
  563. User.reset_notifications_preferences!(current_user)
  564. render json: { message: 'ok' }, status: :ok
  565. end
  566. =begin
  567. Resource:
  568. PUT /api/v1/users/out_of_office
  569. Payload:
  570. {
  571. "out_of_office": true,
  572. "out_of_office_start_at": true,
  573. "out_of_office_end_at": true,
  574. "out_of_office_replacement_id": 123,
  575. "out_of_office_text": 'honeymoon'
  576. }
  577. Response:
  578. {
  579. :message => 'ok'
  580. }
  581. Test:
  582. 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}'
  583. =end
  584. def out_of_office
  585. user = User.find(current_user.id)
  586. user.with_lock do
  587. user.assign_attributes(
  588. out_of_office: params[:out_of_office],
  589. out_of_office_start_at: params[:out_of_office_start_at],
  590. out_of_office_end_at: params[:out_of_office_end_at],
  591. out_of_office_replacement_id: params[:out_of_office_replacement_id],
  592. )
  593. user.preferences[:out_of_office_text] = params[:out_of_office_text]
  594. user.save!
  595. end
  596. render json: { message: 'ok' }, status: :ok
  597. end
  598. =begin
  599. Resource:
  600. DELETE /api/v1/users/account
  601. Payload:
  602. {
  603. "provider": "twitter",
  604. "uid": 581482342942
  605. }
  606. Response:
  607. {
  608. :message => 'ok'
  609. }
  610. Test:
  611. curl http://localhost/api/v1/users/account -v -u #{login}:#{password} -H "Content-Type: application/json" -X PUT -d '{"provider": "twitter", "uid": 581482342942}'
  612. =end
  613. def account_remove
  614. # provider + uid to remove
  615. raise Exceptions::UnprocessableEntity, 'provider needed!' if !params[:provider]
  616. raise Exceptions::UnprocessableEntity, 'uid needed!' if !params[:uid]
  617. # remove from database
  618. record = Authorization.where(
  619. user_id: current_user.id,
  620. provider: params[:provider],
  621. uid: params[:uid],
  622. )
  623. raise Exceptions::UnprocessableEntity, __('No record found!') if !record.first
  624. record.destroy_all
  625. render json: { message: 'ok' }, status: :ok
  626. end
  627. =begin
  628. Resource:
  629. GET /api/v1/users/image/8d6cca1c6bdc226cf2ba131e264ca2c7
  630. Response:
  631. <IMAGE>
  632. Test:
  633. curl http://localhost/api/v1/users/image/8d6cca1c6bdc226cf2ba131e264ca2c7 -v -u #{login}:#{password}
  634. =end
  635. def image
  636. # Cache images in the browser.
  637. expires_in(1.year.from_now, must_revalidate: true)
  638. file = Avatar.get_by_hash(params[:hash])
  639. if file
  640. file_content_type = file.preferences['Content-Type'] || file.preferences['Mime-Type']
  641. return serve_default_image if ActiveStorage.content_types_allowed_inline.exclude?(file_content_type)
  642. send_data(
  643. file.content,
  644. filename: file.filename,
  645. type: file_content_type,
  646. disposition: 'inline'
  647. )
  648. return
  649. end
  650. serve_default_image
  651. end
  652. =begin
  653. Resource:
  654. POST /api/v1/users/avatar
  655. Payload:
  656. {
  657. "avatar_full": "base64 url",
  658. }
  659. Response:
  660. {
  661. message: 'ok'
  662. }
  663. Test:
  664. curl http://localhost/api/v1/users/avatar -v -u #{login}:#{password} -H "Content-Type: application/json" -X POST -d '{"avatar": "base64 url"}'
  665. =end
  666. def avatar_new
  667. service = Service::Avatar::ImageValidate.new
  668. file_full = service.execute(image_data: params[:avatar_full])
  669. if file_full[:error].present?
  670. render json: { error: file_full[:message] }, status: :unprocessable_entity
  671. return
  672. end
  673. file_resize = service.execute(image_data: params[:avatar_resize])
  674. if file_resize[:error].present?
  675. render json: { error: file_resize[:message] }, status: :unprocessable_entity
  676. return
  677. end
  678. render json: { avatar: Service::Avatar::Add.new(current_user: current_user).execute(full_image: file_full, resize_image: file_resize) }, status: :ok
  679. end
  680. def avatar_set_default
  681. # get & validate image
  682. raise Exceptions::UnprocessableEntity, __("The required parameter 'id' is missing.") if !params[:id]
  683. # set as default
  684. avatar = Avatar.set_default('User', current_user.id, params[:id])
  685. # update user link
  686. user = User.find(current_user.id)
  687. user.update!(image: avatar.store_hash)
  688. render json: {}, status: :ok
  689. end
  690. def avatar_destroy
  691. # get & validate image
  692. raise Exceptions::UnprocessableEntity, __("The required parameter 'id' is missing.") if !params[:id]
  693. # remove avatar
  694. Avatar.remove_one('User', current_user.id, params[:id])
  695. # update user link
  696. avatar = Avatar.get_default('User', current_user.id)
  697. user = User.find(current_user.id)
  698. user.update!(image: avatar.store_hash)
  699. render json: {}, status: :ok
  700. end
  701. def avatar_list
  702. # list of avatars
  703. result = Avatar.list('User', current_user.id)
  704. render json: { avatars: result }, status: :ok
  705. end
  706. # @path [GET] /users/import_example
  707. #
  708. # @summary Download of example CSV file.
  709. # @notes The requester have 'admin.user' permissions to be able to download it.
  710. # @example curl -u 'me@example.com:test' http://localhost:3000/api/v1/users/import_example
  711. #
  712. # @response_message 200 File download.
  713. # @response_message 403 Forbidden / Invalid session.
  714. def import_example
  715. send_data(
  716. User.csv_example,
  717. filename: 'user-example.csv',
  718. type: 'text/csv',
  719. disposition: 'attachment'
  720. )
  721. end
  722. # @path [POST] /users/import
  723. #
  724. # @summary Starts import.
  725. # @notes The requester have 'admin.text_module' permissions to be create a new import.
  726. # @example curl -u 'me@example.com:test' -F 'file=@/path/to/file/users.csv' 'https://your.zammad/api/v1/users/import?try=true'
  727. # @example curl -u 'me@example.com:test' -F 'file=@/path/to/file/users.csv' 'https://your.zammad/api/v1/users/import'
  728. #
  729. # @response_message 201 Import started.
  730. # @response_message 403 Forbidden / Invalid session.
  731. def import_start
  732. string = params[:data]
  733. if string.blank? && params[:file].present?
  734. string = params[:file].read.force_encoding('utf-8')
  735. end
  736. raise Exceptions::UnprocessableEntity, __('No source data submitted!') if string.blank?
  737. result = User.csv_import(
  738. string: string,
  739. parse_params: {
  740. col_sep: params[:col_sep] || ',',
  741. },
  742. try: params[:try],
  743. delete: params[:delete],
  744. )
  745. render json: result, status: :ok
  746. end
  747. def two_factor_enabled_authentication_methods
  748. user = User.find(params[:id])
  749. render json: { methods: user.two_factor_enabled_authentication_methods }, status: :ok
  750. end
  751. private
  752. def password_login?
  753. return true if Setting.get('user_show_password_login')
  754. return true if Setting.where('name LIKE ? AND frontend = true', "#{SqlHelper.quote_like('auth_')}%")
  755. .map { |provider| provider.state_current['value'] }
  756. .all?(false)
  757. false
  758. end
  759. def clean_user_params
  760. User.param_cleanup(User.association_name_to_id_convert(params), true).merge(screen: 'create')
  761. end
  762. # @summary Creates a User record with the provided attribute values.
  763. # @notes For creating a user via agent interface
  764. #
  765. # @parameter User(required,body) [User] The attribute value structure needed to create a User record.
  766. #
  767. # @response_message 200 [User] Created User record.
  768. # @response_message 403 Forbidden / Invalid session.
  769. def create_internal
  770. # permission check
  771. check_attributes_by_current_user_permission(params)
  772. user = User.new(clean_user_params)
  773. user.associations_from_param(params)
  774. user.save!
  775. if params[:invite].present?
  776. token = Token.create(action: 'PasswordReset', user_id: user.id)
  777. NotificationFactory::Mailer.notification(
  778. template: 'user_invite',
  779. user: user,
  780. objects: {
  781. token: token,
  782. user: user,
  783. current_user: current_user,
  784. }
  785. )
  786. end
  787. if response_expand?
  788. user = user.reload.attributes_with_association_names
  789. user.delete('password')
  790. render json: user, status: :created
  791. return
  792. end
  793. if response_full?
  794. result = {
  795. id: user.id,
  796. assets: user.assets({}),
  797. }
  798. render json: result, status: :created
  799. return
  800. end
  801. user = user.reload.attributes_with_association_ids
  802. user.delete('password')
  803. render json: user, status: :created
  804. end
  805. # @summary Creates a User record with the provided attribute values.
  806. # @notes For creating a user via public signup form
  807. #
  808. # @parameter User(required,body) [User] The attribute value structure needed to create a User record.
  809. #
  810. # @response_message 200 [User] Created User record.
  811. # @response_message 403 Forbidden / Invalid session.
  812. def create_signup
  813. # check signup option only after admin account is created
  814. if !params[:signup]
  815. raise Exceptions::UnprocessableEntity, __("The required parameter 'signup' is missing.")
  816. end
  817. # only allow fixed fields
  818. # TODO: https://github.com/zammad/zammad/issues/3295
  819. new_params = clean_user_params.slice(:firstname, :lastname, :email, :password)
  820. # check if user already exists
  821. if new_params[:email].blank?
  822. raise Exceptions::UnprocessableEntity, __("The required attribute 'email' is missing.")
  823. end
  824. signup = Service::User::Deprecated::Signup.new(user_data: new_params)
  825. begin
  826. signup.execute
  827. rescue PasswordPolicy::Error => e
  828. render json: { error: e.message }, status: :unprocessable_entity
  829. return
  830. rescue Service::CheckFeatureEnabled::FeatureDisabledError => e
  831. raise Exceptions::UnprocessableEntity, e.message
  832. end
  833. render json: { message: 'ok' }, status: :created
  834. end
  835. # @summary Creates a User record with the provided attribute values.
  836. # @notes For creating an administrator account when setting up the system
  837. #
  838. # @parameter User(required,body) [User] The attribute value structure needed to create a User record.
  839. #
  840. # @response_message 200 [User] Created User record.
  841. # @response_message 403 Forbidden / Invalid session.
  842. def create_admin
  843. Service::User::AddFirstAdmin.new.execute(
  844. user_data: clean_user_params.slice(:firstname, :lastname, :email, :password),
  845. request: request,
  846. )
  847. render json: { message: 'ok' }, status: :created
  848. rescue PasswordPolicy::Error => e
  849. render json: { error: e.message }, status: :unprocessable_entity
  850. rescue Exceptions::MissingAttribute, Service::System::CheckSetup::SystemSetupError => e
  851. raise Exceptions::UnprocessableEntity, e.message
  852. end
  853. def serve_default_image
  854. image = 'R0lGODdhMAAwAOMAAMzMzJaWlr6+vqqqqqOjo8XFxbe3t7GxsZycnAAAAAAAAAAAAAAAAAAAAAAAAAAAACwAAAAAMAAwAAAEcxDISau9OOvNu/9gKI5kaZ5oqq5s675wLM90bd94ru98TwuAA+KQAQqJK8EAgBAgMEqmkzUgBIeSwWGZtR5XhSqAULACCoGCJGwlm1MGQrq9RqgB8fm4ZTUgDBIEcRR9fz6HiImKi4yNjo+QkZKTlJWWkBEAOw=='
  855. send_data(
  856. Base64.decode64(image),
  857. filename: 'image.gif',
  858. type: 'image/gif',
  859. disposition: 'inline'
  860. )
  861. end
  862. end