users_controller.rb 31 KB

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