Nessuna descrizione

auth_controller.rb 2.1KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. class AuthController < ApplicationController
  2. def render_data(data, status)
  3. render json: data, status: status, callback: params[:callback]
  4. end
  5. def render_error(message, status = :unprocessable_entity)
  6. render_data({ error: message }, status)
  7. end
  8. def render_success(data, status = :ok)
  9. if data.is_a? String
  10. render_data({ message: data }, status)
  11. else
  12. render_data(data, status)
  13. end
  14. end
  15. def signup
  16. @user = User.create auth_params
  17. render json: { token: Token.encode(@user.id) }
  18. end
  19. def login
  20. @user = User.find_by email: params[:email] if params[:email].present?
  21. if @user && @user.authenticate(params[:password])
  22. render json: { token: Token.encode(@user.id) }
  23. else
  24. render json: { message: 'Invalid credentials' }, status: :unauthorized
  25. end
  26. end
  27. def authenticate
  28. @oauth = "Oauth::#{params['provider'].titleize}".constantize.new(params)
  29. if @oauth.authorized?
  30. @user = User.from_auth(@oauth.formatted_user_data, current_user)
  31. if @user
  32. render_success(token: Token.encode(@user.id), id: @user.id)
  33. else
  34. render_error "This #{params[:provider]} account is used already"
  35. end
  36. else
  37. render_error("There was an error with #{params['provider']}. please try again.")
  38. end
  39. end
  40. # Twitter don't support auth2 protocol yet, so it has it's own implementation for now
  41. def twitter
  42. if params[:oauth_token].blank?
  43. render_success({ oauth_token: twitter_oauth.request_token })
  44. else
  45. render_success({ token: twitter_oauth.access_token })
  46. end
  47. end
  48. def twitter_step_2
  49. if twitter_oauth.authorized?
  50. if User.from_auth(twitter_oauth.formatted_account_info, current_user)
  51. render_success("connected twitter to profile successfuly")
  52. else
  53. render_error "This twitter account is used already"
  54. end
  55. else
  56. render_error("There was an error with twitter. please try again.")
  57. end
  58. end
  59. private
  60. def twitter_oauth
  61. @oauth ||= Oauth::Twitter.new(params)
  62. end
  63. def auth_params
  64. params.require(:auth).permit(:email, :password, :displayName)
  65. end
  66. end