Created
April 20, 2020 16:56
-
-
Save benhickson/2b3f97fd2df4d70ba1442f2788a8ee19 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class UsersController < ApplicationController | |
skip_before_action :authenticate_request, only: [:anon] | |
# create/register a user | |
def create | |
# transition anonymous account to full account | |
updateStatus = @current_user.update(email: params[:email], display_name: params[:display_name], password: params[:password]) | |
if updateStatus | |
# delete the associated anonymous user | |
@current_user.anonymous_user.destroy | |
render json: {status: 'User created successfully'}, status: :created | |
else | |
render json: {errors: @current_user.errors.full_messages}, status: :conflict | |
end | |
end | |
# login a user | |
def login | |
if @current_user.anonymous_user | |
# TODO: Stretch Goal: associate anonymous User’s actions around the site | |
# with the already-existing user they’re logging in as. This will involve | |
# any records in the database for the anonymous user to the already-existing | |
# user's ID, and recording some kind of record of this for any external | |
# services that involve user_id’s and can’t be updated. | |
end | |
# get a user by the email supplied | |
user = User.find_by(email: params[:email].to_s.downcase) | |
# check that the user exists and the password is correct | |
if user && user.authenticate(params[:password]) | |
render json: {auth_token: JsonWebToken.encode({user_id: user.id})}, status: :ok | |
else | |
render json: {error: 'Invalid email or password'}, status: :unauthorized | |
end | |
end | |
# create and login an anonymous user | |
def anon | |
new_anon_user = User.create | |
AnonymousUser.create(display_name: AnonymousUser.random_name, user: new_anon_user) | |
render json: {auth_token: JsonWebToken.encode({user_id: new_anon_user.id})}, status: :ok | |
end | |
def current | |
user = @current_user | |
render json: { | |
email: user.email, | |
display_name: user.display_name, | |
anon_display_name: user.anon_display_name | |
}, status: :ok | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment