Class: Api::V1::TokensController

Inherits:
BaseController show all
Defined in:
app/controllers/api/v1/tokens_controller.rb

Instance Method Summary collapse

Methods inherited from BaseController

#add_generic_headers!, #authenticate_api_user!, #authenticate_user_from_simple_token!, #force_json!

Instance Method Details

#createObject


25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'app/controllers/api/v1/tokens_controller.rb', line 25

def create
  email = params[:email]
  password = params[:password]

  if email.blank? || password.blank?
    render status: :bad_request, json: { message: 'The request must contain the user email and password.' }
    return
  end

  unless @user = User.find_by(email: email.downcase)
    logger.info("User #{email} failed signin, user cannot be found.")
    render status: :unauthorized, json: { message: 'Invalid email or password.' }
    return
  end

  if @user.valid_password?(password)
    # This following line forbids simultaneous connections:
    if @user.authentication_token.blank?
      @user.update_column(:authentication_token, User.generate_authentication_token)
    end
    render json: { token: @user.authentication_token }
  else
    logger.info("User #{email} failed signin, password is invalid")
    render status: :unauthorized, json: { message: 'Invalid email or password.' }
  end
end

#destroyObject


52
53
54
55
56
57
58
59
60
61
# File 'app/controllers/api/v1/tokens_controller.rb', line 52

def destroy
  @user = User.find_by(authentication_token: params[:id])
  if @user
    @user.update_column(:authentication_token, nil)
    render status: :ok, json: { token: params[:id] }
  else
    logger.info('Token not found.')
    render status: :not_found, json: { message: 'Invalid token.' }
  end
end