users_controller.rb 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697
  1. # Copyright (C) 2012-2014 Zammad Foundation, http://zammad-foundation.org/
  2. class UsersController < ApplicationController
  3. before_filter :authentication_check, :except => [:create, :password_reset_send, :password_reset_verify]
  4. # @path [GET] /users
  5. #
  6. # @summary Returns a list of Users.
  7. # @notes Requester has to be in role 'Admin' or 'Agent' to
  8. # get a list of all Users. If requester is only in the
  9. # role 'Customer' he gets only his own Users entity.
  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. if is_role('Customer') && !is_role('Admin') && !is_role('Agent')
  16. users = User.where( :id => current_user.id )
  17. else
  18. users = 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 with the requested identifier.
  29. # @notes Requester has to be in role 'Admin' or 'Agent' to
  30. # get a list of all Users. If requester is only in the
  31. # role 'Customer' he gets only his own Users entity.
  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] )
  47. render :json => user
  48. end
  49. # @path [POST] /users
  50. #
  51. # @summary Creates a User with the provided attribute values.
  52. # @notes TODO.
  53. #
  54. # @parameter User(required,body) [User] The attribute value structure needed to create a User.
  55. #
  56. # @response_message 200 [User] Created User record.
  57. # @response_message 401 Invalid session.
  58. def create
  59. user = User.new( User.param_cleanup(params) )
  60. begin
  61. # check if it's first user
  62. count = User.all.count()
  63. # if it's a signup, add user to customer role
  64. if !current_user
  65. user.updated_by_id = 1
  66. user.created_by_id = 1
  67. # check if feature is enabled
  68. if !Setting.get('user_create_account')
  69. render :json => { :error => 'Feature not enabled!' }, :status => :unprocessable_entity
  70. return
  71. end
  72. # add first user as admin/agent and to all groups
  73. group_ids = []
  74. role_ids = []
  75. if count <= 2
  76. Role.where( :name => [ 'Admin', 'Agent'] ).each { |role|
  77. role_ids.push role.id
  78. }
  79. Group.all().each { |group|
  80. group_ids.push group.id
  81. }
  82. # everybody else will go as customer per default
  83. else
  84. role_ids.push Role.where( :name => 'Customer' ).first.id
  85. end
  86. user.role_ids = role_ids
  87. user.group_ids = group_ids
  88. # else do assignment as defined
  89. else
  90. # permission check by role
  91. return if !permission_check_by_role
  92. if params[:role_ids]
  93. user.role_ids = params[:role_ids]
  94. end
  95. if params[:group_ids]
  96. user.group_ids = params[:group_ids]
  97. end
  98. end
  99. # check if user already exists
  100. if user.email
  101. exists = User.where( :email => user.email ).first
  102. if exists
  103. render :json => { :error => 'User already exists!' }, :status => :unprocessable_entity
  104. return
  105. end
  106. end
  107. user.save
  108. # if first user was added, set system init done
  109. if count <= 2
  110. Setting.set( 'system_init_done', true )
  111. end
  112. # send inviteation if needed / only if session exists
  113. if params[:invite] && current_user
  114. # generate token
  115. token = Token.create( :action => 'PasswordReset', :user_id => user.id )
  116. # send mail
  117. data = {}
  118. data[:subject] = 'Invitation to #{config.product_name} at #{config.fqdn}'
  119. data[:body] = 'Hi #{user.firstname},
  120. I (#{current_user.firstname} #{current_user.lastname}) invite you to #{config.product_name} - the customer support / ticket system platform.
  121. Click on the following link and set your password:
  122. #{config.http_type}://#{config.fqdn}/#password_reset_verify/#{token.name}
  123. Enjoy,
  124. #{current_user.firstname} #{current_user.lastname}
  125. Your #{config.product_name} Team
  126. '
  127. # prepare subject & body
  128. [:subject, :body].each { |key|
  129. data[key.to_sym] = NotificationFactory.build(
  130. :locale => user.locale,
  131. :string => data[key.to_sym],
  132. :objects => {
  133. :token => token,
  134. :user => user,
  135. :current_user => current_user,
  136. }
  137. )
  138. }
  139. # send notification
  140. NotificationFactory.send(
  141. :recipient => user,
  142. :subject => data[:subject],
  143. :body => data[:body]
  144. )
  145. end
  146. user_new = User.find( user.id )
  147. render :json => user_new, :status => :created
  148. rescue Exception => e
  149. render :json => { :error => e.message }, :status => :unprocessable_entity
  150. end
  151. end
  152. # @path [PUT] /users/{id}
  153. #
  154. # @summary Updates the User matching the identifier with the provided attribute values.
  155. # @notes TODO.
  156. #
  157. # @parameter id(required) [Integer] The identifier matching the requested User.
  158. # @parameter User(required,body) [User] The attribute value structure needed to update a User.
  159. #
  160. # @response_message 200 [User] Updated User record.
  161. # @response_message 401 Invalid session.
  162. def update
  163. # access deny
  164. return if !permission_check
  165. user = User.find( params[:id] )
  166. begin
  167. user.update_attributes( User.param_cleanup(params) )
  168. # only allow Admin's and Agent's
  169. if is_role('Admin') && is_role('Agent') && params[:role_ids]
  170. user.role_ids = params[:role_ids]
  171. end
  172. # only allow Admin's
  173. if is_role('Admin') && params[:group_ids]
  174. user.group_ids = params[:group_ids]
  175. end
  176. # only allow Admin's and Agent's
  177. if is_role('Admin') && is_role('Agent') && params[:organization_ids]
  178. user.organization_ids = params[:organization_ids]
  179. end
  180. # get new data
  181. user_new = User.find( params[:id] )
  182. render :json => user_new, :status => :ok
  183. rescue Exception => e
  184. render :json => { :error => e.message }, :status => :unprocessable_entity
  185. end
  186. end
  187. # @path [DELETE] /users/{id}
  188. #
  189. # @summary Deletes the User matching the identifier.
  190. # @notes Requester has to be in role 'Admin' to be able to delete a User.
  191. #
  192. # @parameter id(required) [User] The identifier matching the requested User.
  193. #
  194. # @response_message 200 User successfully deleted.
  195. # @response_message 401 Invalid session.
  196. def destroy
  197. return if deny_if_not_role('Admin')
  198. model_destory_render(User, params)
  199. end
  200. # @path [GET] /users/search
  201. #
  202. # @tag Search
  203. # @tag User
  204. #
  205. # @summary Searches the User matching the given expression(s).
  206. # @notes TODO: It's possible to use the SOLR search syntax.
  207. # Requester has to be in role 'Admin' or 'Agent' to
  208. # be able to search Users. If requester is only in the
  209. # role 'Customer' he gets a permission denied message.
  210. #
  211. # @parameter term [String] The search term.
  212. # @parameter limit [Integer] The limit of search results.
  213. # @parameter role_ids(multi) [Array<String>] A list of Role identifiers to which the Users have to be allocated to.
  214. # @parameter full [Boolean] Defines if the result should be
  215. # true: { user_ids => [1,2,...], assets => {...} }
  216. # or false: [{:id => user.id, :label => "firstname lastname <email>", :value => "firstname lastname <email>"},...].
  217. #
  218. # @response_message 200 [Array<User>] A list of User resources matching the search term.
  219. # @response_message 401 Invalid session.
  220. def search
  221. if is_role('Customer') && !is_role('Admin') && !is_role('Agent')
  222. response_access_deny
  223. return
  224. end
  225. query_params = {
  226. :query => params[:term],
  227. :limit => params[:limit],
  228. :current_user => current_user,
  229. }
  230. if params[:role_ids] && !params[:role_ids].empty?
  231. query_params[:role_ids] = params[:role_ids]
  232. end
  233. # do query
  234. user_all = User.search(query_params)
  235. # build result list
  236. if !params[:full]
  237. users = []
  238. user_all.each { |user|
  239. realname = user.firstname.to_s + ' ' + user.lastname.to_s
  240. if user.email && user.email.to_s != ''
  241. realname = realname + ' <' + user.email.to_s + '>'
  242. end
  243. a = { :id => user.id, :label => realname, :value => realname }
  244. users.push a
  245. }
  246. # return result
  247. render :json => users
  248. return
  249. end
  250. user_ids = []
  251. assets = {}
  252. user_all.each { |user|
  253. assets = user.assets(assets)
  254. user_ids.push user.id
  255. }
  256. # return result
  257. render :json => {
  258. :assets => assets,
  259. :user_ids => user_ids.uniq,
  260. }
  261. end
  262. # @path [GET] /users/history/{id}
  263. #
  264. # @tag History
  265. # @tag User
  266. #
  267. # @summary Returns the History of a User matching the given identifier.
  268. # @notes Requester has to be in role 'Admin' or 'Agent' to
  269. # get the history of a User.
  270. #
  271. # @parameter id(required) [Integer] The identifier matching the requested User.
  272. #
  273. # @response_message 200 [History] The History ressource of the requested User.
  274. # @response_message 401 Invalid session.
  275. def history
  276. # permissin check
  277. if !is_role('Admin') && !is_role('Agent')
  278. response_access_deny
  279. return
  280. end
  281. # get user data
  282. user = User.find( params[:id] )
  283. # get history of user
  284. history = user.history_get(true)
  285. # return result
  286. render :json => history
  287. end
  288. =begin
  289. Resource:
  290. POST /api/v1/users/password_reset
  291. Payload:
  292. {
  293. "username": "some user name"
  294. }
  295. Response:
  296. {
  297. :message => 'ok'
  298. }
  299. Test:
  300. curl http://localhost/api/v1/users/password_reset.json -v -u #{login}:#{password} -H "Content-Type: application/json" -X POST -d '{"username": "some_username"}'
  301. =end
  302. def password_reset_send
  303. # check if feature is enabled
  304. if !Setting.get('user_lost_password')
  305. render :json => { :error => 'Feature not enabled!' }, :status => :unprocessable_entity
  306. return
  307. end
  308. success = User.password_reset_send( params[:username] )
  309. if success
  310. render :json => { :message => 'ok' }, :status => :ok
  311. else
  312. render :json => { :message => 'failed' }, :status => :unprocessable_entity
  313. end
  314. end
  315. =begin
  316. Resource:
  317. POST /api/v1/users/password_reset_verify
  318. Payload:
  319. {
  320. "token": "SoMeToKeN",
  321. "password" "new_password"
  322. }
  323. Response:
  324. {
  325. :message => 'ok'
  326. }
  327. Test:
  328. 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"}'
  329. =end
  330. def password_reset_verify
  331. if params[:password]
  332. user = User.password_reset_via_token( params[:token], params[:password] )
  333. else
  334. user = User.password_reset_check( params[:token] )
  335. end
  336. if user
  337. render :json => { :message => 'ok', :user_login => user.login }, :status => :ok
  338. else
  339. render :json => { :message => 'failed' }, :status => :unprocessable_entity
  340. end
  341. end
  342. =begin
  343. Resource:
  344. POST /api/v1/users/password_change
  345. Payload:
  346. {
  347. "password_old": "some_password_old",
  348. "password_new": "some_password_new"
  349. }
  350. Response:
  351. {
  352. :message => 'ok'
  353. }
  354. Test:
  355. 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"}'
  356. =end
  357. def password_change
  358. # check old password
  359. if !params[:password_old]
  360. render :json => { :message => 'Old password needed!' }, :status => :unprocessable_entity
  361. return
  362. end
  363. user = User.authenticate( current_user.login, params[:password_old] )
  364. if !user
  365. render :json => { :message => 'Old password is wrong!' }, :status => :unprocessable_entity
  366. return
  367. end
  368. # set new password
  369. if !params[:password_new]
  370. render :json => { :message => 'New password needed!' }, :status => :unprocessable_entity
  371. return
  372. end
  373. user.update_attributes( :password => params[:password_new] )
  374. render :json => { :message => 'ok', :user_login => user.login }, :status => :ok
  375. end
  376. =begin
  377. Resource:
  378. PUT /api/v1/users/preferences.json
  379. Payload:
  380. {
  381. "language": "de",
  382. "notification": true
  383. }
  384. Response:
  385. {
  386. :message => 'ok'
  387. }
  388. Test:
  389. curl http://localhost/api/v1/users/preferences.json -v -u #{login}:#{password} -H "Content-Type: application/json" -X PUT -d '{"language": "de", "notifications": true}'
  390. =end
  391. def preferences
  392. if !current_user
  393. render :json => { :message => 'No current user!' }, :status => :unprocessable_entity
  394. return
  395. end
  396. if params[:user]
  397. params[:user].each {|key, value|
  398. current_user.preferences[key.to_sym] = value
  399. }
  400. end
  401. current_user.save
  402. render :json => { :message => 'ok' }, :status => :ok
  403. end
  404. =begin
  405. Resource:
  406. DELETE /api/v1/users/account.json
  407. Payload:
  408. {
  409. "provider": "twitter",
  410. "uid": 581482342942
  411. }
  412. Response:
  413. {
  414. :message => 'ok'
  415. }
  416. Test:
  417. curl http://localhost/api/v1/users/account.json -v -u #{login}:#{password} -H "Content-Type: application/json" -X PUT -d '{"provider": "twitter", "uid": 581482342942}'
  418. =end
  419. def account_remove
  420. if !current_user
  421. render :json => { :message => 'No current user!' }, :status => :unprocessable_entity
  422. return
  423. end
  424. # provider + uid to remove
  425. if !params[:provider]
  426. render :json => { :message => 'provider needed!' }, :status => :unprocessable_entity
  427. return
  428. end
  429. if !params[:uid]
  430. render :json => { :message => 'uid needed!' }, :status => :unprocessable_entity
  431. return
  432. end
  433. # remove from database
  434. record = Authorization.where(
  435. :user_id => current_user.id,
  436. :provider => params[:provider],
  437. :uid => params[:uid],
  438. )
  439. if !record.first
  440. render :json => { :message => 'No record found!' }, :status => :unprocessable_entity
  441. return
  442. end
  443. record.destroy_all
  444. render :json => { :message => 'ok' }, :status => :ok
  445. end
  446. =begin
  447. Resource:
  448. GET /api/v1/users/image/8d6cca1c6bdc226cf2ba131e264ca2c7
  449. Response:
  450. <IMAGE>
  451. Test:
  452. curl http://localhost/api/v1/users/image/8d6cca1c6bdc226cf2ba131e264ca2c7 -v -u #{login}:#{password}
  453. =end
  454. def image
  455. # cache image
  456. response.headers['Expires'] = 1.year.from_now.httpdate
  457. response.headers['Cache-Control'] = 'cache, store, max-age=31536000, must-revalidate'
  458. response.headers['Pragma'] = 'cache'
  459. file = Avatar.get_by_hash( params[:hash] )
  460. if file
  461. send_data(
  462. file.content,
  463. :filename => file.filename,
  464. :type => file.preferences['Content-Type'] || file.preferences['Mime-Type'],
  465. :disposition => 'inline'
  466. )
  467. return
  468. end
  469. # serve default image
  470. image = 'R0lGODdhMAAwAOMAAMzMzJaWlr6+vqqqqqOjo8XFxbe3t7GxsZycnAAAAAAAAAAAAAAAAAAAAAAAAAAAACwAAAAAMAAwAAAEcxDISau9OOvNu/9gKI5kaZ5oqq5s675wLM90bd94ru98TwuAA+KQAQqJK8EAgBAgMEqmkzUgBIeSwWGZtR5XhSqAULACCoGCJGwlm1MGQrq9RqgB8fm4ZTUgDBIEcRR9fz6HiImKi4yNjo+QkZKTlJWWkBEAOw=='
  471. send_data(
  472. Base64.decode64(image),
  473. :filename => 'image.gif',
  474. :type => 'image/gif',
  475. :disposition => 'inline'
  476. )
  477. end
  478. =begin
  479. Resource:
  480. POST /api/v1/users/avatar
  481. Payload:
  482. {
  483. "avatar_full": "base64 url",
  484. }
  485. Response:
  486. {
  487. :message => 'ok'
  488. }
  489. Test:
  490. curl http://localhost/api/v1/users/avatar -v -u #{login}:#{password} -H "Content-Type: application/json" -X POST -d '{"avatar": "base64 url"}'
  491. =end
  492. def avatar_new
  493. return if !valid_session_with_user
  494. # get & validate image
  495. file_full = StaticAssets.data_url_attributes( params[:avatar_full] )
  496. file_resize = StaticAssets.data_url_attributes( params[:avatar_resize] )
  497. avatar = Avatar.add(
  498. :object => 'User',
  499. :o_id => current_user.id,
  500. :full => {
  501. :content => file_full[:content],
  502. :mime_type => file_full[:mime_type],
  503. },
  504. :resize => {
  505. :content => file_resize[:content],
  506. :mime_type => file_resize[:mime_type],
  507. },
  508. :source => 'upload ' + Time.now.to_s,
  509. :deletable => true,
  510. )
  511. # update user link
  512. current_user.update_attributes( :image => avatar.store_hash )
  513. render :json => { :avatar => avatar }, :status => :ok
  514. end
  515. def avatar_set_default
  516. return if !valid_session_with_user
  517. # get & validate image
  518. if !params[:id]
  519. render :json => { :message => 'No id of avatar!' }, :status => :unprocessable_entity
  520. return
  521. end
  522. # set as default
  523. avatar = Avatar.set_default( 'User', current_user.id, params[:id] )
  524. # update user link
  525. current_user.update_attributes( :image => avatar.store_hash )
  526. render :json => {}, :status => :ok
  527. end
  528. def avatar_destroy
  529. return if !valid_session_with_user
  530. # get & validate image
  531. if !params[:id]
  532. render :json => { :message => 'No id of avatar!' }, :status => :unprocessable_entity
  533. return
  534. end
  535. # remove avatar
  536. Avatar.remove_one( 'User', current_user.id, params[:id] )
  537. # update user link
  538. avatar = Avatar.get_default( 'User', current_user.id )
  539. current_user.update_attributes( :image => avatar.store_hash )
  540. render :json => {}, :status => :ok
  541. end
  542. def avatar_list
  543. return if !valid_session_with_user
  544. # list of avatars
  545. result = Avatar.list( 'User', current_user.id )
  546. render :json => { :avatars => result }, :status => :ok
  547. end
  548. private
  549. def permission_check_by_role
  550. return true if is_role('Admin')
  551. return true if is_role('Agent')
  552. response_access_deny
  553. return false
  554. end
  555. def permission_check
  556. return true if is_role('Admin')
  557. return true if is_role('Agent')
  558. # allow to update customer by him self
  559. return true if is_role('Customer') && params[:id].to_i == current_user.id
  560. response_access_deny
  561. return false
  562. end
  563. end