users_controller.rb 28 KB

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