users_controller.rb 28 KB

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