users_controller.rb 26 KB

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