Would love some feedback on this simple API implementation with Ruby on Rails. Have I used proper naming conventions, readable/manageable code, optimal approaches, etc? As I'm still learning Ruby on rails, I'd love to hear what other fellow engineers have to say about this :)
A simple Register API:
require 'net/http'
require 'uri'
require 'json'
class V1::UsersController < ApplicationController
protect_from_forgery with: :null_session
def register
name = params[:name]
email = params[:email]
password = params[:password]
@existing_user = User.find_by(email: params[:email])
if @existing_user == nil
@user = User.new(
name: name,
email: email,
password: password,
plan: "FREE"
)
#save user
if @user.save!
#generate auth token
@auth = save_new_auth @user.id
render :json => {
:user => @user.as_json(:except => [:created_at, :updated_at, :password, :stripe_id, :subscription_id, :id, :email]),
:auth => @auth
}
else
render json: {"error" => "Unprocessable Entity"}
end
else
render json: { error: { type: "UNAUTHORIZED", message: "Looks like you already have an account. Please login 👋" } }, status: 403
end
end
Login API:
def login
email = params[:email]
password = params[:password]
@auth = nil
@user = User.find_by(email: params[:email], password: password)
if @user == nil
render json: { error: { type: "UNAUTHORIZED", message: "Invalid Login Credentials 🤔" } }, status: 401
else
@auth = UserAuth.find_by(user_id: @user.id)
if @auth == nil
@auth = save_new_auth @user.id
end
render :json => {
:user => @user.as_json(:except => [:created_at, :updated_at, :password, :stripe_id, :subscription_id, :id, :email]),
:auth => @auth
}
end
end
Access token Generator:
def save_new_auth (user_id)
@auth = UserAuth.new(
access_token: generate_token,
user_id: user_id,
status: true
)
@auth.save
return @auth
end
def generate_token(size = 28)
charset = %w{ 2 3 4 6 7 9 A C D E F G H J K M N P Q R T V W X Y Z}
(0...size).map{ charset.to_a[rand(charset.size)] }.join
end