users_controller.rb 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685
  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>] Matching Users.
  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. # GET /api/v1/users/history/1
  263. def history
  264. # permissin check
  265. if !is_role('Admin') && !is_role('Agent')
  266. response_access_deny
  267. return
  268. end
  269. # get user data
  270. user = User.find( params[:id] )
  271. # get history of user
  272. history = user.history_get(true)
  273. # return result
  274. render :json => history
  275. end
  276. =begin
  277. Resource:
  278. POST /api/v1/users/password_reset
  279. Payload:
  280. {
  281. "username": "some user name"
  282. }
  283. Response:
  284. {
  285. :message => 'ok'
  286. }
  287. Test:
  288. curl http://localhost/api/v1/users/password_reset.json -v -u #{login}:#{password} -H "Content-Type: application/json" -X POST -d '{"username": "some_username"}'
  289. =end
  290. def password_reset_send
  291. # check if feature is enabled
  292. if !Setting.get('user_lost_password')
  293. render :json => { :error => 'Feature not enabled!' }, :status => :unprocessable_entity
  294. return
  295. end
  296. success = User.password_reset_send( params[:username] )
  297. if success
  298. render :json => { :message => 'ok' }, :status => :ok
  299. else
  300. render :json => { :message => 'failed' }, :status => :unprocessable_entity
  301. end
  302. end
  303. =begin
  304. Resource:
  305. POST /api/v1/users/password_reset_verify
  306. Payload:
  307. {
  308. "token": "SoMeToKeN",
  309. "password" "new_password"
  310. }
  311. Response:
  312. {
  313. :message => 'ok'
  314. }
  315. Test:
  316. 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"}'
  317. =end
  318. def password_reset_verify
  319. if params[:password]
  320. user = User.password_reset_via_token( params[:token], params[:password] )
  321. else
  322. user = User.password_reset_check( params[:token] )
  323. end
  324. if user
  325. render :json => { :message => 'ok', :user_login => user.login }, :status => :ok
  326. else
  327. render :json => { :message => 'failed' }, :status => :unprocessable_entity
  328. end
  329. end
  330. =begin
  331. Resource:
  332. POST /api/v1/users/password_change
  333. Payload:
  334. {
  335. "password_old": "some_password_old",
  336. "password_new": "some_password_new"
  337. }
  338. Response:
  339. {
  340. :message => 'ok'
  341. }
  342. Test:
  343. 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"}'
  344. =end
  345. def password_change
  346. # check old password
  347. if !params[:password_old]
  348. render :json => { :message => 'Old password needed!' }, :status => :unprocessable_entity
  349. return
  350. end
  351. user = User.authenticate( current_user.login, params[:password_old] )
  352. if !user
  353. render :json => { :message => 'Old password is wrong!' }, :status => :unprocessable_entity
  354. return
  355. end
  356. # set new password
  357. if !params[:password_new]
  358. render :json => { :message => 'New password needed!' }, :status => :unprocessable_entity
  359. return
  360. end
  361. user.update_attributes( :password => params[:password_new] )
  362. render :json => { :message => 'ok', :user_login => user.login }, :status => :ok
  363. end
  364. =begin
  365. Resource:
  366. PUT /api/v1/users/preferences.json
  367. Payload:
  368. {
  369. "language": "de",
  370. "notification": true
  371. }
  372. Response:
  373. {
  374. :message => 'ok'
  375. }
  376. Test:
  377. curl http://localhost/api/v1/users/preferences.json -v -u #{login}:#{password} -H "Content-Type: application/json" -X PUT -d '{"language": "de", "notifications": true}'
  378. =end
  379. def preferences
  380. if !current_user
  381. render :json => { :message => 'No current user!' }, :status => :unprocessable_entity
  382. return
  383. end
  384. if params[:user]
  385. params[:user].each {|key, value|
  386. current_user.preferences[key.to_sym] = value
  387. }
  388. end
  389. current_user.save
  390. render :json => { :message => 'ok' }, :status => :ok
  391. end
  392. =begin
  393. Resource:
  394. DELETE /api/v1/users/account.json
  395. Payload:
  396. {
  397. "provider": "twitter",
  398. "uid": 581482342942
  399. }
  400. Response:
  401. {
  402. :message => 'ok'
  403. }
  404. Test:
  405. curl http://localhost/api/v1/users/account.json -v -u #{login}:#{password} -H "Content-Type: application/json" -X PUT -d '{"provider": "twitter", "uid": 581482342942}'
  406. =end
  407. def account_remove
  408. if !current_user
  409. render :json => { :message => 'No current user!' }, :status => :unprocessable_entity
  410. return
  411. end
  412. # provider + uid to remove
  413. if !params[:provider]
  414. render :json => { :message => 'provider needed!' }, :status => :unprocessable_entity
  415. return
  416. end
  417. if !params[:uid]
  418. render :json => { :message => 'uid needed!' }, :status => :unprocessable_entity
  419. return
  420. end
  421. # remove from database
  422. record = Authorization.where(
  423. :user_id => current_user.id,
  424. :provider => params[:provider],
  425. :uid => params[:uid],
  426. )
  427. if !record.first
  428. render :json => { :message => 'No record found!' }, :status => :unprocessable_entity
  429. return
  430. end
  431. record.destroy_all
  432. render :json => { :message => 'ok' }, :status => :ok
  433. end
  434. =begin
  435. Resource:
  436. GET /api/v1/users/image/8d6cca1c6bdc226cf2ba131e264ca2c7
  437. Response:
  438. <IMAGE>
  439. Test:
  440. curl http://localhost/api/v1/users/image/8d6cca1c6bdc226cf2ba131e264ca2c7 -v -u #{login}:#{password}
  441. =end
  442. def image
  443. # cache image
  444. response.headers['Expires'] = 1.year.from_now.httpdate
  445. response.headers['Cache-Control'] = 'cache, store, max-age=31536000, must-revalidate'
  446. response.headers['Pragma'] = 'cache'
  447. file = Avatar.get_by_hash( params[:hash] )
  448. if file
  449. send_data(
  450. file.content,
  451. :filename => file.filename,
  452. :type => file.preferences['Content-Type'] || file.preferences['Mime-Type'],
  453. :disposition => 'inline'
  454. )
  455. return
  456. end
  457. # serve default image
  458. image = 'R0lGODdhMAAwAOMAAMzMzJaWlr6+vqqqqqOjo8XFxbe3t7GxsZycnAAAAAAAAAAAAAAAAAAAAAAAAAAAACwAAAAAMAAwAAAEcxDISau9OOvNu/9gKI5kaZ5oqq5s675wLM90bd94ru98TwuAA+KQAQqJK8EAgBAgMEqmkzUgBIeSwWGZtR5XhSqAULACCoGCJGwlm1MGQrq9RqgB8fm4ZTUgDBIEcRR9fz6HiImKi4yNjo+QkZKTlJWWkBEAOw=='
  459. send_data(
  460. Base64.decode64(image),
  461. :filename => 'image.gif',
  462. :type => 'image/gif',
  463. :disposition => 'inline'
  464. )
  465. end
  466. =begin
  467. Resource:
  468. POST /api/v1/users/avatar
  469. Payload:
  470. {
  471. "avatar_full": "base64 url",
  472. }
  473. Response:
  474. {
  475. :message => 'ok'
  476. }
  477. Test:
  478. curl http://localhost/api/v1/users/avatar -v -u #{login}:#{password} -H "Content-Type: application/json" -X POST -d '{"avatar": "base64 url"}'
  479. =end
  480. def avatar_new
  481. return if !valid_session_with_user
  482. # get & validate image
  483. file_full = StaticAssets.data_url_attributes( params[:avatar_full] )
  484. file_resize = StaticAssets.data_url_attributes( params[:avatar_resize] )
  485. avatar = Avatar.add(
  486. :object => 'User',
  487. :o_id => current_user.id,
  488. :full => {
  489. :content => file_full[:content],
  490. :mime_type => file_full[:mime_type],
  491. },
  492. :resize => {
  493. :content => file_resize[:content],
  494. :mime_type => file_resize[:mime_type],
  495. },
  496. :source => 'upload ' + Time.now.to_s,
  497. :deletable => true,
  498. )
  499. # update user link
  500. current_user.update_attributes( :image => avatar.store_hash )
  501. render :json => { :avatar => avatar }, :status => :ok
  502. end
  503. def avatar_set_default
  504. return if !valid_session_with_user
  505. # get & validate image
  506. if !params[:id]
  507. render :json => { :message => 'No id of avatar!' }, :status => :unprocessable_entity
  508. return
  509. end
  510. # set as default
  511. avatar = Avatar.set_default( 'User', current_user.id, params[:id] )
  512. # update user link
  513. current_user.update_attributes( :image => avatar.store_hash )
  514. render :json => {}, :status => :ok
  515. end
  516. def avatar_destroy
  517. return if !valid_session_with_user
  518. # get & validate image
  519. if !params[:id]
  520. render :json => { :message => 'No id of avatar!' }, :status => :unprocessable_entity
  521. return
  522. end
  523. # remove avatar
  524. Avatar.remove_one( 'User', current_user.id, params[:id] )
  525. # update user link
  526. avatar = Avatar.get_default( 'User', current_user.id )
  527. current_user.update_attributes( :image => avatar.store_hash )
  528. render :json => {}, :status => :ok
  529. end
  530. def avatar_list
  531. return if !valid_session_with_user
  532. # list of avatars
  533. result = Avatar.list( 'User', current_user.id )
  534. render :json => { :avatars => result }, :status => :ok
  535. end
  536. private
  537. def permission_check_by_role
  538. return true if is_role('Admin')
  539. return true if is_role('Agent')
  540. response_access_deny
  541. return false
  542. end
  543. def permission_check
  544. return true if is_role('Admin')
  545. return true if is_role('Agent')
  546. # allow to update customer by him self
  547. return true if is_role('Customer') && params[:id].to_i == current_user.id
  548. response_access_deny
  549. return false
  550. end
  551. end