|
| 1 | +module Api |
| 2 | + module V1 |
| 3 | + class AuthController < BaseController |
| 4 | + skip_before_action :authenticate_request!, only: [:register, :login, :forgot_password, :reset_password, :refresh] |
| 5 | + |
| 6 | + # POST /api/v1/auth/register |
| 7 | + def register |
| 8 | + ActiveRecord::Base.transaction do |
| 9 | + organization = create_organization! |
| 10 | + user = create_user!(organization) |
| 11 | + tokens = Authentication::Services::JwtService.generate_tokens(user) |
| 12 | + |
| 13 | + # Log audit action with user's organization |
| 14 | + AuditLog.create!( |
| 15 | + organization: organization, |
| 16 | + user: user, |
| 17 | + action: 'register', |
| 18 | + entity_type: 'User', |
| 19 | + entity_id: user.id, |
| 20 | + ip_address: request.remote_ip, |
| 21 | + user_agent: request.user_agent |
| 22 | + ) |
| 23 | + |
| 24 | + render_created( |
| 25 | + { |
| 26 | + user: JSON.parse(UserSerializer.render(user)), |
| 27 | + organization: JSON.parse(OrganizationSerializer.render(organization)), |
| 28 | + **tokens |
| 29 | + }, |
| 30 | + message: 'Registration successful' |
| 31 | + ) |
| 32 | + end |
| 33 | + rescue ActiveRecord::RecordInvalid => e |
| 34 | + render_validation_errors(e) |
| 35 | + rescue => e |
| 36 | + render_error(message: 'Registration failed', code: 'REGISTRATION_ERROR') |
| 37 | + end |
| 38 | + |
| 39 | + # POST /api/v1/auth/login |
| 40 | + def login |
| 41 | + user = authenticate_user! |
| 42 | + |
| 43 | + if user |
| 44 | + tokens = Authentication::Services::JwtService.generate_tokens(user) |
| 45 | + user.update_last_login! |
| 46 | + |
| 47 | + # Log audit action with user's organization |
| 48 | + AuditLog.create!( |
| 49 | + organization: user.organization, |
| 50 | + user: user, |
| 51 | + action: 'login', |
| 52 | + entity_type: 'User', |
| 53 | + entity_id: user.id, |
| 54 | + ip_address: request.remote_ip, |
| 55 | + user_agent: request.user_agent |
| 56 | + ) |
| 57 | + |
| 58 | + render_success( |
| 59 | + { |
| 60 | + user: JSON.parse(UserSerializer.render(user)), |
| 61 | + organization: JSON.parse(OrganizationSerializer.render(user.organization)), |
| 62 | + **tokens |
| 63 | + }, |
| 64 | + message: 'Login successful' |
| 65 | + ) |
| 66 | + else |
| 67 | + render_error( |
| 68 | + message: 'Invalid email or password', |
| 69 | + code: 'INVALID_CREDENTIALS', |
| 70 | + status: :unauthorized |
| 71 | + ) |
| 72 | + end |
| 73 | + end |
| 74 | + |
| 75 | + # POST /api/v1/auth/refresh |
| 76 | + def refresh |
| 77 | + refresh_token = params[:refresh_token] |
| 78 | + |
| 79 | + if refresh_token.blank? |
| 80 | + return render_error( |
| 81 | + message: 'Refresh token is required', |
| 82 | + code: 'MISSING_REFRESH_TOKEN', |
| 83 | + status: :bad_request |
| 84 | + ) |
| 85 | + end |
| 86 | + |
| 87 | + begin |
| 88 | + tokens = Authentication::Services::JwtService.refresh_access_token(refresh_token) |
| 89 | + render_success(tokens, message: 'Token refreshed successfully') |
| 90 | + rescue Authentication::Services::JwtService::AuthenticationError => e |
| 91 | + render_error( |
| 92 | + message: e.message, |
| 93 | + code: 'INVALID_REFRESH_TOKEN', |
| 94 | + status: :unauthorized |
| 95 | + ) |
| 96 | + end |
| 97 | + end |
| 98 | + |
| 99 | + # POST /api/v1/auth/logout |
| 100 | + def logout |
| 101 | + # For JWT, we don't need to do anything server-side for logout |
| 102 | + # The client should remove the token |
| 103 | + |
| 104 | + log_user_action( |
| 105 | + action: 'logout', |
| 106 | + entity_type: 'User', |
| 107 | + entity_id: current_user.id |
| 108 | + ) |
| 109 | + |
| 110 | + render_success({}, message: 'Logout successful') |
| 111 | + end |
| 112 | + |
| 113 | + # POST /api/v1/auth/forgot-password |
| 114 | + def forgot_password |
| 115 | + email = params[:email]&.downcase&.strip |
| 116 | + |
| 117 | + if email.blank? |
| 118 | + return render_error( |
| 119 | + message: 'Email is required', |
| 120 | + code: 'MISSING_EMAIL', |
| 121 | + status: :bad_request |
| 122 | + ) |
| 123 | + end |
| 124 | + |
| 125 | + user = User.find_by(email: email) |
| 126 | + |
| 127 | + if user |
| 128 | + # Generate password reset token |
| 129 | + reset_token = generate_reset_token(user) |
| 130 | + |
| 131 | + # Here you would send an email with the reset token |
| 132 | + # For now, we'll just return success |
| 133 | + |
| 134 | + AuditLog.create!( |
| 135 | + organization: user.organization, |
| 136 | + user: user, |
| 137 | + action: 'password_reset_requested', |
| 138 | + entity_type: 'User', |
| 139 | + entity_id: user.id, |
| 140 | + ip_address: request.remote_ip, |
| 141 | + user_agent: request.user_agent |
| 142 | + ) |
| 143 | + end |
| 144 | + |
| 145 | + # Always return success to prevent email enumeration |
| 146 | + render_success( |
| 147 | + {}, |
| 148 | + message: 'If the email exists, a password reset link has been sent' |
| 149 | + ) |
| 150 | + end |
| 151 | + |
| 152 | + # POST /api/v1/auth/reset-password |
| 153 | + def reset_password |
| 154 | + token = params[:token] |
| 155 | + new_password = params[:password] |
| 156 | + password_confirmation = params[:password_confirmation] |
| 157 | + |
| 158 | + if token.blank? || new_password.blank? |
| 159 | + return render_error( |
| 160 | + message: 'Token and password are required', |
| 161 | + code: 'MISSING_PARAMETERS', |
| 162 | + status: :bad_request |
| 163 | + ) |
| 164 | + end |
| 165 | + |
| 166 | + if new_password != password_confirmation |
| 167 | + return render_error( |
| 168 | + message: 'Password confirmation does not match', |
| 169 | + code: 'PASSWORD_MISMATCH', |
| 170 | + status: :bad_request |
| 171 | + ) |
| 172 | + end |
| 173 | + |
| 174 | + user = verify_reset_token(token) |
| 175 | + |
| 176 | + if user |
| 177 | + user.update!(password: new_password) |
| 178 | + |
| 179 | + AuditLog.create!( |
| 180 | + organization: user.organization, |
| 181 | + user: user, |
| 182 | + action: 'password_reset_completed', |
| 183 | + entity_type: 'User', |
| 184 | + entity_id: user.id, |
| 185 | + ip_address: request.remote_ip, |
| 186 | + user_agent: request.user_agent |
| 187 | + ) |
| 188 | + |
| 189 | + render_success({}, message: 'Password reset successful') |
| 190 | + else |
| 191 | + render_error( |
| 192 | + message: 'Invalid or expired reset token', |
| 193 | + code: 'INVALID_RESET_TOKEN', |
| 194 | + status: :bad_request |
| 195 | + ) |
| 196 | + end |
| 197 | + end |
| 198 | + |
| 199 | + # GET /api/v1/auth/me |
| 200 | + def me |
| 201 | + render_success( |
| 202 | + { |
| 203 | + user: JSON.parse(UserSerializer.render(current_user)), |
| 204 | + organization: JSON.parse(OrganizationSerializer.render(current_organization)) |
| 205 | + } |
| 206 | + ) |
| 207 | + end |
| 208 | + |
| 209 | + private |
| 210 | + |
| 211 | + def create_organization! |
| 212 | + Organization.create!(organization_params) |
| 213 | + end |
| 214 | + |
| 215 | + def create_user!(organization) |
| 216 | + User.create!(user_params.merge( |
| 217 | + organization: organization, |
| 218 | + role: 'owner' # First user is always the owner |
| 219 | + )) |
| 220 | + end |
| 221 | + |
| 222 | + def authenticate_user! |
| 223 | + email = params[:email]&.downcase&.strip |
| 224 | + password = params[:password] |
| 225 | + |
| 226 | + return nil if email.blank? || password.blank? |
| 227 | + |
| 228 | + user = User.find_by(email: email) |
| 229 | + user&.authenticate(password) ? user : nil |
| 230 | + end |
| 231 | + |
| 232 | + def organization_params |
| 233 | + params.require(:organization).permit(:name, :region, :tier) |
| 234 | + end |
| 235 | + |
| 236 | + def user_params |
| 237 | + params.require(:user).permit(:email, :password, :full_name, :timezone, :language) |
| 238 | + end |
| 239 | + |
| 240 | + def generate_reset_token(user) |
| 241 | + # In a real app, you'd store this token in the database or Redis |
| 242 | + # For now, we'll use JWT with a short expiration |
| 243 | + payload = { |
| 244 | + user_id: user.id, |
| 245 | + type: 'password_reset', |
| 246 | + exp: 1.hour.from_now.to_i, |
| 247 | + iat: Time.current.to_i |
| 248 | + } |
| 249 | + |
| 250 | + JWT.encode(payload, Authentication::Services::JwtService::SECRET_KEY, 'HS256') |
| 251 | + end |
| 252 | + |
| 253 | + def verify_reset_token(token) |
| 254 | + begin |
| 255 | + decoded = JWT.decode(token, Authentication::Services::JwtService::SECRET_KEY, true, { algorithm: 'HS256' }) |
| 256 | + payload = HashWithIndifferentAccess.new(decoded[0]) |
| 257 | + |
| 258 | + return nil unless payload[:type] == 'password_reset' |
| 259 | + |
| 260 | + User.find(payload[:user_id]) |
| 261 | + rescue JWT::DecodeError, JWT::ExpiredSignature, ActiveRecord::RecordNotFound |
| 262 | + nil |
| 263 | + end |
| 264 | + end |
| 265 | + end |
| 266 | + end |
| 267 | +end |
0 commit comments