module ApiUserAuth # Registration/Login controller class AuthController < ActionController::API rescue_from Exceptions::Unauthorized, with: :auth_user_unauthorized rescue_from Exceptions::WrongParams, with: :auth_user_wrong_params rescue_from ApiUserAuth::Exceptions::ProviderError, with: :auth_user_provider rescue_from ::ActiveRecord::RecordNotFound, with: :auth_user_not_found def create auth_user = AuthUser.create_by_params(base_params) render json: auth_user.to_json, status: 201 end def login auth_user = AuthUser.login_by_params(base_params) render json: auth_user.to_json, status: 200 end def password auth_user = AuthUser.update_password( params.permit(:email, :password, :code).to_h ) render json: auth_user.to_json, status: 200 end def forgot_password auth_user = AuthUser.forgot_password( params.permit(:email) ) render json: auth_user.to_json end def logout if request.headers['Authorization'].blank? raise Exceptions::Unauthorized, 'Header [Authorization] can not be blank!' end token = request.headers['Authorization'].sub(/Bearer\s*=?/, '') auth_user = AuthUser.find_fy_token(token) if auth_user.present? && auth_user.logout(token) render json: {}, status: 200 else render json: {}, status: 400 end end def provider auth_user = AuthUser.create_by_provider(params) render json: auth_user.to_json end def add_provider if request.headers['Authorization'].blank? raise Exceptions::Unauthorized, 'Header [Authorization] can not be blank!' end token = request.headers['Authorization'].sub(/Bearer\s*=?/, '') auth_user = AuthUser.find_fy_token(token) if auth_user.present? if auth_user.add_provider_login(params) render json: auth_user.as_user_json, status: 200 else render json: {}, status: 400 end else render json: {}, status: 400 end end private def base_params params.permit(:email, :password).to_h end def auth_user_not_found render json: {}, status: 404 end def auth_user_unauthorized(exception) render json: { message: exception.message || 'Unauthorized' }, status: 401 end def auth_user_provider(exception) render json: { message: exception.message }, status: 422 end def auth_user_wrong_params(exception) render json: { message: exception.message }, status: 422 end end end