diff --git a/.github/workflows/linters.yml b/.github/workflows/linters.yml index cfe811d..2a4ea62 100644 --- a/.github/workflows/linters.yml +++ b/.github/workflows/linters.yml @@ -6,9 +6,9 @@ env: FORCE_COLOR: 1 jobs: - rubocop: + rubocop: name: Rubocop - runs-on: ub stylelint:untu-18.04 + runs-on: ubuntu-18.04 steps: - uses: actions/checkout@v2 - uses: actions/setup-ruby@v1 diff --git a/Gemfile b/Gemfile index fdbbe02..a5335fb 100644 --- a/Gemfile +++ b/Gemfile @@ -1,16 +1,16 @@ -source "https://rubygems.org" +source 'https://rubygems.org' git_source(:github) { |repo| "https://github.com/#{repo}.git" } -ruby "3.1.2" +ruby '3.1.2' # Bundle edge Rails instead: gem "rails", github: "rails/rails", branch: "main" -gem "rails", "~> 7.0.3", ">= 7.0.3.1" +gem 'rails', '~> 7.0.3', '>= 7.0.3.1' # Use postgresql as the database for Active Record -gem "pg", "~> 1.1" +gem 'pg', '~> 1.1' # Use the Puma web server [https://github.com/puma/puma] -gem "puma", "~> 5.0" +gem 'puma', '~> 5.0' # Build JSON APIs with ease [https://github.com/rails/jbuilder] # gem "jbuilder" @@ -25,20 +25,24 @@ gem "puma", "~> 5.0" # gem "bcrypt", "~> 3.1.7" # Windows does not include zoneinfo files, so bundle the tzinfo-data gem -gem "tzinfo-data", platforms: %i[ mingw mswin x64_mingw jruby ] +gem 'tzinfo-data', platforms: %i[mingw mswin x64_mingw jruby] # Reduces boot times through caching; required in config/boot.rb -gem "bootsnap", require: false +gem 'bootsnap', require: false # Use Active Storage variants [https://guides.rubyonrails.org/active_storage_overview.html#transforming-images] # gem "image_processing", "~> 1.2" # Use Rack CORS for handling Cross-Origin Resource Sharing (CORS), making cross-origin AJAX possible -# gem "rack-cors" +gem 'rack-cors' group :development, :test do # See https://guides.rubyonrails.org/debugging_rails_applications.html#debugging-with-the-debug-gem - gem "debug", platforms: %i[ mri mingw x64_mingw ] + gem 'bullet' + gem 'database_cleaner' + gem 'debug', platforms: %i[mri mingw x64_mingw] + gem 'rails-controller-testing' + gem 'rspec-rails' end group :development do @@ -46,3 +50,7 @@ group :development do # gem "spring" end +gem 'cancancan' +gem 'devise' +gem 'devise-jwt' +gem 'fast_jsonapi' diff --git a/Gemfile.lock b/Gemfile.lock index 7eed066..e100f7f 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -66,16 +66,48 @@ GEM i18n (>= 1.6, < 2) minitest (>= 5.1) tzinfo (~> 2.0) + bcrypt (3.1.18) bootsnap (1.13.0) msgpack (~> 1.2) builder (3.2.4) + bullet (7.0.3) + activesupport (>= 3.0.0) + uniform_notifier (~> 1.11) + cancancan (3.4.0) concurrent-ruby (1.1.10) crass (1.0.6) + database_cleaner (2.0.1) + database_cleaner-active_record (~> 2.0.0) + database_cleaner-active_record (2.0.1) + activerecord (>= 5.a) + database_cleaner-core (~> 2.0.0) + database_cleaner-core (2.0.1) debug (1.6.2) irb (>= 1.3.6) reline (>= 0.3.1) + devise (4.8.1) + bcrypt (~> 3.0) + orm_adapter (~> 0.1) + railties (>= 4.1.0) + responders + warden (~> 1.2.3) + devise-jwt (0.9.0) + devise (~> 4.0) + warden-jwt_auth (~> 0.6) + diff-lcs (1.5.0) digest (3.1.0) + dry-auto_inject (0.9.0) + dry-container (>= 0.3.4) + dry-configurable (0.15.0) + concurrent-ruby (~> 1.0) + dry-core (~> 0.6) + dry-container (0.10.1) + concurrent-ruby (~> 1.0) + dry-core (0.8.1) + concurrent-ruby (~> 1.0) erubi (1.11.0) + fast_jsonapi (1.5) + activesupport (>= 4.2) globalid (1.0.0) activesupport (>= 5.0) i18n (1.12.0) @@ -83,6 +115,7 @@ GEM io-console (0.5.11) irb (1.4.1) reline (>= 0.3.0) + jwt (2.4.1) loofah (2.18.0) crass (~> 1.0.2) nokogiri (>= 1.5.9) @@ -110,11 +143,14 @@ GEM nio4r (2.5.8) nokogiri (1.13.8-x86_64-linux) racc (~> 1.4) + orm_adapter (0.5.0) pg (1.4.3) puma (5.6.4) nio4r (~> 2.0) racc (1.6.0) rack (2.2.4) + rack-cors (1.1.1) + rack (>= 2.0.0) rack-test (2.0.2) rack (>= 1.3) rails (7.0.3.1) @@ -131,6 +167,10 @@ GEM activesupport (= 7.0.3.1) bundler (>= 1.15.0) railties (= 7.0.3.1) + rails-controller-testing (1.0.5) + actionpack (>= 5.0.1.rc1) + actionview (>= 5.0.1.rc1) + activesupport (>= 5.0.1.rc1) rails-dom-testing (2.0.3) activesupport (>= 4.2.0) nokogiri (>= 1.6) @@ -146,11 +186,39 @@ GEM rake (13.0.6) reline (0.3.1) io-console (~> 0.5) + responders (3.0.1) + actionpack (>= 5.0) + railties (>= 5.0) + rspec-core (3.11.0) + rspec-support (~> 3.11.0) + rspec-expectations (3.11.0) + diff-lcs (>= 1.2.0, < 2.0) + rspec-support (~> 3.11.0) + rspec-mocks (3.11.1) + diff-lcs (>= 1.2.0, < 2.0) + rspec-support (~> 3.11.0) + rspec-rails (5.1.2) + actionpack (>= 5.2) + activesupport (>= 5.2) + railties (>= 5.2) + rspec-core (~> 3.10) + rspec-expectations (~> 3.10) + rspec-mocks (~> 3.10) + rspec-support (~> 3.10) + rspec-support (3.11.0) strscan (3.0.4) thor (1.2.1) timeout (0.3.0) tzinfo (2.0.5) concurrent-ruby (~> 1.0) + uniform_notifier (1.16.0) + warden (1.2.9) + rack (>= 2.0.9) + warden-jwt_auth (0.6.0) + dry-auto_inject (~> 0.8) + dry-configurable (~> 0.13) + jwt (~> 2.1) + warden (~> 1.2) websocket-driver (0.7.5) websocket-extensions (>= 0.1.0) websocket-extensions (0.1.5) @@ -161,10 +229,19 @@ PLATFORMS DEPENDENCIES bootsnap + bullet + cancancan + database_cleaner debug + devise + devise-jwt + fast_jsonapi pg (~> 1.1) puma (~> 5.0) + rack-cors rails (~> 7.0.3, >= 7.0.3.1) + rails-controller-testing + rspec-rails tzinfo-data RUBY VERSION diff --git a/app/controllers/api/v1/mentors/registrations_controller.rb b/app/controllers/api/v1/mentors/registrations_controller.rb new file mode 100644 index 0000000..0e1858d --- /dev/null +++ b/app/controllers/api/v1/mentors/registrations_controller.rb @@ -0,0 +1,85 @@ +class Api::V1::Mentors::RegistrationsController < Devise::RegistrationsController + # before_action :configure_sign_up_params, only: [:create] + # before_action :configure_account_update_params, only: [:update] + respond_to :json + + # GET /resource/sign_up + # def new + # super + # end + + # POST /resource + def create + build_resource(sign_up_params) + + resource.save + + if resource.persisted? + render json: { message: 'Signed up successfully' }, status: :created + else + render json: { errors: resource.errors }, status: :unprocessable_entity + end + end + + # GET /resource/edit + # def edit + # super + # end + + # PUT /resource + # def update + # super + # end + + # DELETE /resource + # def destroy + # super + # end + + # GET /resource/cancel + # Forces the session data which is usually expired after sign + # in to be expired now. This is useful if the user wants to + # cancel oauth signing in/up in the middle of the process, + # removing all OAuth session data. + # def cancel + # super + # end + + # protected + + # If you have extra params to permit, append them to the sanitizer. + # def configure_sign_up_params + # devise_parameter_sanitizer.permit(:sign_up, keys: [:attribute]) + # end + + # If you have extra params to permit, append them to the sanitizer. + # def configure_account_update_params + # devise_parameter_sanitizer.permit(:account_update, keys: [:attribute]) + # end + + # The path used after sign up. + # def after_sign_up_path_for(resource) + # super(resource) + # end + + # The path used after sign up for inactive accounts. + # def after_inactive_sign_up_path_for(resource) + # super(resource) + # end + + private + + def respond_with(resource, _opts = {}) + register_success && return if resource.persisted? + + register_failed + end + + def register_success + render json: { message: 'Signed up successfully.' }, status: :ok + end + + def register_failed + render json: { message: 'Something went wrong.' }, status: :unprocessable_entity + end +end diff --git a/app/controllers/api/v1/mentors/sessions_controller.rb b/app/controllers/api/v1/mentors/sessions_controller.rb new file mode 100644 index 0000000..087d2fa --- /dev/null +++ b/app/controllers/api/v1/mentors/sessions_controller.rb @@ -0,0 +1,59 @@ +class Api::V1::Mentors::SessionsController < Devise::SessionsController + # before_action :configure_sign_in_params, only: [:create] + respond_to :json + + def create + possible_aud = request.headers['HTTP_JWT_AUD'].presence || request.headers['JWT_AUD'].presence + self.resource = warden.authenticate!(auth_options) + sign_in(resource_name, resource) + if mentor_signed_in? + last = resource.allowlisted_mentors_jwts.where(aud: possible_aud).last + aud = possible_aud || 'UNKNOWN' + + if last.present? + last.update_columns({ + browser_data: params[:browser], + os_data: params[:os], + remote_ip: params[:ip] + }) + aud = last.aud + end + + respond_with(resource, { aud: }) + else + render json: resource.errors, status: 401 + end + rescue StandardError + render json: { errors: I18n.t('api.oops') }, status: 500 + end + + private + + def current_token + request.env['warden-jwt_auth.token'] + end + + def respond_with(resource, opts = {}) + render json: { + mentor: resource, + jwt: current_token, + aud: opts[:aud] + } + end + + def respond_to_on_destroy + render json: { message: 'Signed out successfully' } + end + + # DELETE /resource/sign_out + # def destroy + # super + # end + + # protected + + # If you have extra params to permit, append them to the sanitizer. + # def configure_sign_in_params + # devise_parameter_sanitizer.permit(:sign_in, keys: [:attribute]) + # end +end diff --git a/app/controllers/api/v1/users/registrations_controller.rb b/app/controllers/api/v1/users/registrations_controller.rb new file mode 100644 index 0000000..6f9cdf7 --- /dev/null +++ b/app/controllers/api/v1/users/registrations_controller.rb @@ -0,0 +1,31 @@ +class Api::V1::Users::RegistrationsController < Devise::RegistrationsController + respond_to :json + + def create + build_resource(sign_up_params) + + resource.save + + if resource.persisted? + render json: { message: 'Signed up successfully' }, status: :created + else + render json: { errors: resource.errors }, status: :unprocessable_entity + end + end + + private + + def respond_with(resource, _opts = {}) + register_success && return if resource.persisted? + + register_failed + end + + def register_success + render json: { message: 'Signed up successfully.' }, status: :ok + end + + def register_failed + render json: { message: 'Something went wrong.' }, status: :unprocessable_entity + end +end diff --git a/app/controllers/api/v1/users/sessions_controller.rb b/app/controllers/api/v1/users/sessions_controller.rb new file mode 100644 index 0000000..40df946 --- /dev/null +++ b/app/controllers/api/v1/users/sessions_controller.rb @@ -0,0 +1,85 @@ +class Api::V1::Users::SessionsController < Devise::SessionsController + respond_to :json + # before_action :configure_sign_in_params, only: [:create] + + # GET /resource/sign_in + # def new + # super + # end + + # POST /resource/sign_in + def create + possible_aud = request.headers['HTTP_JWT_AUD'].presence || request.headers['JWT_AUD'].presence + self.resource = warden.authenticate!(auth_options) + sign_in(resource_name, resource) + if user_signed_in? + last = resource.allowlisted_jwts.where(aud: possible_aud).last + aud = possible_aud || 'UNKNOWN' + + if last.present? + last.update_columns({ + browser_data: params[:browser], + os_data: params[:os], + remote_ip: params[:ip] + }) + aud = last.aud + end + + respond_with(resource, { aud: }) + else + render json: resource.errors, status: 401 + end + rescue StandardError + render json: { errors: I18n.t('api.oops') }, status: 500 + end + + private + + def current_token + request.env['warden-jwt_auth.token'] + end + + def respond_with(resource, opts = {}) + render json: { + user: resource, + jwt: current_token, + aud: opts[:aud] + } + end + + def respond_to_on_destroy + render json: { message: 'Signed out successfully' } + end + + # DELETE /resource/sign_out + # def destroy + # super + # end + + # protected + + # If you have extra params to permit, append them to the sanitizer. + # def configure_sign_in_params + # devise_parameter_sanitizer.permit(:sign_in, keys: [:attribute]) + # end + + # private + + # def respond_with(resource, _opts = {}) + # render json: {message: 'You are logged in.'}, status: :ok + # end + + # def respond_to_on_destroy + # log_out_success && return if current_user + + # log_out_failure + # end + + # def log_out_success + # render json: {message: 'You are logged out.'}, status: :ok + # end + + # def log_out_failure + # render json: {message: 'You are not logged in.'}, status: :unauthorized + # end +end diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index 4ac8823..eae550f 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -1,2 +1,8 @@ class ApplicationController < ActionController::API + before_action :configure_permited_parameters, if: :devise_controller? + + def configure_permited_parameters + devise_parameter_sanitizer.permit(:sign_up, keys: [:email]) + devise_parameter_sanitizer.permit(:sign_in, keys: [:email]) + end end diff --git a/app/mailers/admin_mailer.rb b/app/mailers/admin_mailer.rb new file mode 100644 index 0000000..fe37cf5 --- /dev/null +++ b/app/mailers/admin_mailer.rb @@ -0,0 +1,9 @@ +class AdminMailer < ApplicationMailer + default from: 'zmekonnen59@gmail.com' + layout 'mailer' + + def new_mentor_waiting_for_approval(email) + @email = email + mail(to: 'zmekonnen59@gmail.com', subject: 'New user awaiting admin approval') + end +end diff --git a/app/mailers/application_mailer.rb b/app/mailers/application_mailer.rb index 3c34c81..286b223 100644 --- a/app/mailers/application_mailer.rb +++ b/app/mailers/application_mailer.rb @@ -1,4 +1,4 @@ class ApplicationMailer < ActionMailer::Base - default from: "from@example.com" - layout "mailer" + default from: 'from@example.com' + layout 'mailer' end diff --git a/app/models/ability.rb b/app/models/ability.rb new file mode 100644 index 0000000..155e128 --- /dev/null +++ b/app/models/ability.rb @@ -0,0 +1,17 @@ +class Ability + include CanCan::Ability + + def initialize(user) + case user.class.name + when 'Mentor' + can :manage, :all + when 'User' + case user.role == 'admin' + when true + can :manage, :all + when false + can :read, :all + end + end + end +end diff --git a/app/models/allowlisted_jwt.rb b/app/models/allowlisted_jwt.rb new file mode 100644 index 0000000..73dadd2 --- /dev/null +++ b/app/models/allowlisted_jwt.rb @@ -0,0 +1,2 @@ +class AllowlistedJwt < ApplicationRecord +end diff --git a/app/models/allowlisted_mentors_jwt.rb b/app/models/allowlisted_mentors_jwt.rb new file mode 100644 index 0000000..b64e768 --- /dev/null +++ b/app/models/allowlisted_mentors_jwt.rb @@ -0,0 +1,2 @@ +class AllowlistedMentorsJwt < ApplicationRecord +end diff --git a/app/models/application_record.rb b/app/models/application_record.rb index b63caeb..10a4cba 100644 --- a/app/models/application_record.rb +++ b/app/models/application_record.rb @@ -1,3 +1,3 @@ class ApplicationRecord < ActiveRecord::Base - primary_abstract_class + self.abstract_class = true end diff --git a/app/models/concerns/mentors/allowlist_mentors.rb b/app/models/concerns/mentors/allowlist_mentors.rb new file mode 100644 index 0000000..5447429 --- /dev/null +++ b/app/models/concerns/mentors/allowlist_mentors.rb @@ -0,0 +1,40 @@ +module Mentors::AllowlistMentors + extend ActiveSupport::Concern + + included do + has_many :allowlisted_mentors_jwts, dependent: :destroy + + # @see Warden::JWTAuth::Interfaces::RevocationStrategy#jwt_revoked? + def self.jwt_revoked?(payload, mentor) + mentor.allowlisted_mentors_jwts.exists?(payload.slice('jti', 'aud')) + puts "jwt_revoked? #{payload.slice('jti', 'aud')}" + end + + # @see Warden::JWTAuth::Interfaces::RevocationStrategy#revoke_jwt + def self.revoke_jwt(payload, mentor) + jwt = mentor.allowlisted_mentors_jwts.find_by(payload.slice('jti', 'aud')) + jwt&.destroy! + end + end + + # Warden::JWTAuth::Interfaces::User#on_jwt_dispatch + def on_jwt_dispatch(_token, payload) + prev_token = allowlisted_mentors_jwts.where(aud: payload['aud']).where.not(exp: ..Time.now).last + token = allowlisted_mentors_jwts.create!( + jti: payload['jti'], + aud: payload['aud'].presence || 'UNKNOWN', + exp: Time.at(payload['exp'].to_i) + ) + if token.present? && prev_token.present? + token.update_columns({ + browser_data: prev_token.browser_data, + os_data: prev_token.os_data, + remote_ip: prev_token.remote_ip + }) + # NOTE: don't destroy the previous token right away in case + # user opens new tab, or whatever and needs to do something... + # prev_token.destroy! + end + token + end +end diff --git a/app/models/concerns/users/allowlist.rb b/app/models/concerns/users/allowlist.rb new file mode 100644 index 0000000..0031988 --- /dev/null +++ b/app/models/concerns/users/allowlist.rb @@ -0,0 +1,40 @@ +module Users::Allowlist + extend ActiveSupport::Concern + + included do + has_many :allowlisted_jwts, dependent: :destroy + + # @see Warden::JWTAuth::Interfaces::RevocationStrategy#jwt_revoked? + def self.jwt_revoked?(payload, user) + user.allowlisted_jwts.exists?(payload.slice('jti', 'aud')) + puts "jwt_revoked? #{payload.slice('jti', 'aud')}" + end + + # @see Warden::JWTAuth::Interfaces::RevocationStrategy#revoke_jwt + def self.revoke_jwt(payload, user) + jwt = user.allowlisted_jwts.find_by(payload.slice('jti', 'aud')) + jwt&.destroy! + end + end + + # Warden::JWTAuth::Interfaces::User#on_jwt_dispatch + def on_jwt_dispatch(_token, payload) + prev_token = allowlisted_jwts.where(aud: payload['aud']).where.not(exp: ..Time.now).last + token = allowlisted_jwts.create!( + jti: payload['jti'], + aud: payload['aud'].presence || 'UNKNOWN', + exp: Time.at(payload['exp'].to_i) + ) + if token.present? && prev_token.present? + token.update_columns({ + browser_data: prev_token.browser_data, + os_data: prev_token.os_data, + remote_ip: prev_token.remote_ip + }) + # NOTE: don't destroy the previous token right away in case + # user opens new tab, or whatever and needs to do something... + # prev_token.destroy! + end + token + end +end diff --git a/app/models/jwt_denylist.rb b/app/models/jwt_denylist.rb new file mode 100644 index 0000000..47269e4 --- /dev/null +++ b/app/models/jwt_denylist.rb @@ -0,0 +1,5 @@ +class JwtDenylist < ApplicationRecord + include Devise::JWT::RevocationStrategies::Denylist + + self.table_name = 'jwt_denylist' +end diff --git a/app/models/mentor.rb b/app/models/mentor.rb new file mode 100644 index 0000000..84dcc96 --- /dev/null +++ b/app/models/mentor.rb @@ -0,0 +1,24 @@ +class Mentor < ApplicationRecord + after_create :send_admin_mail + + include Mentors::AllowlistMentors + # Include default devise modules. Others available are: + # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable + devise :database_authenticatable, :registerable, + :recoverable, :rememberable, :validatable, + :jwt_authenticatable, jwt_revocation_strategy: self + + has_many :allowlisted_mentors_jwts, dependent: :destroy + + def active_for_authentication? + super && approved? + end + + def inactive_message + approved? ? super : :not_approved + end + + def send_admin_mail + AdminMailer.new_mentor_waiting_for_approval(email).deliver + end +end diff --git a/app/models/user.rb b/app/models/user.rb new file mode 100644 index 0000000..0835e97 --- /dev/null +++ b/app/models/user.rb @@ -0,0 +1,16 @@ +class User < ApplicationRecord + include Users::Allowlist + + devise :database_authenticatable, :registerable, + :rememberable, :validatable, :jwt_authenticatable, + jwt_revocation_strategy: self + + has_many :allowlisted_jwts, dependent: :destroy + + def for_display + { + id:, + email: + } + end +end diff --git a/app/views/admin_mailer/new_mentor_waiting_for_approval.erb b/app/views/admin_mailer/new_mentor_waiting_for_approval.erb new file mode 100644 index 0000000..e405614 --- /dev/null +++ b/app/views/admin_mailer/new_mentor_waiting_for_approval.erb @@ -0,0 +1,2 @@ +
<%= @email %> has registered to join your site!
+An admin can approve this registration by visiting the website and editing the user
\ No newline at end of file diff --git a/config.ru b/config.ru index 4a3c09a..ad1fbf2 100644 --- a/config.ru +++ b/config.ru @@ -1,6 +1,6 @@ # This file is used by Rack-based servers to start the application. -require_relative "config/environment" +require_relative 'config/environment' run Rails.application Rails.application.load_server diff --git a/config/credentials.yml.enc b/config/credentials.yml.enc index d8ed4b5..6a19fb6 100644 --- a/config/credentials.yml.enc +++ b/config/credentials.yml.enc @@ -1 +1 @@ -iX7sffWqXo06QuhApDF9bzX9uD89YZasuWi1QOGESelNmz+LRPct6kx/zbrdb9T+SMIXzcUwt2r2CZ1OrKWJ2Q3lcrUuSpNMormflkyE2CvAGT8Y5xY0fZt5cinQUF7AEhry/c68fP8h15pBz2+og3GJ+//GWo87m7Yc+OuzJlsQwzRW8YIHVOc679xXsbRH2xXb+hBKfQSg5zMEflU2YQPJ5qzocmtosM4WzSbcchqP8/I7tZoC8k8Xw6rg9ntt+L1IhT1hEsyoIBEmGB4lgfwjOZdYKnNOeqfYc9+ALDnPg2GBKF4ne0VTQ3T5F0slZNCK1n9FLUpRJ5fNbkMOa2PtiiC8jQ7d1zIAJ6VZFtibJCbGF78G9Hg7V8HOWuArXhAYeRmfmbbSq3Kd0CpGqcHHLGJLX7Use7JY--a0/TNBIGswNCFU2B--tMdW03+0Jw7zlyuNoWnfOw== \ No newline at end of file +fFlPsK2PW9SiHWEYb7Al6C9nSd5kYQRWgo2XiBqrY//CTIk2mfylGS2ggXbncoWmw6F0JHGfWTrOQkUpLNUju881XrXKQrRswZk5vtZX+aRkUZHNGldJKmwSqLlJ+MuOXLnUmTk0Zg42E/54jD+XvFGhhdhnbiN0RuONDnz1gIi0vjpt2kF9Ims/ryLwdLYkECrSxU/2QsPFeotRMOq6QN/wvBd1A18RtmPh3b/ffXtWJTsFIs3vZ1IgXIJ+KTgH5WUCElHvU5enGP7fMw3qoqE2NCLxiF9Z/0lKtU0oQdVnwq6WAzC8GiusWvGdZJ5kkxj5BF9tyrYwcdWL2q670hxu07nMOBaWHxsLD2tV087hy0eX4lrYldEkKrLZS43IKXQwHlXnfyuP+kQcWD/n43EzCT7wWKxLRtHFPI6Ybf6SqpXrvHh6V+XSbXk/wVk65cKFiD7Sgm/p0ECDgDzrLRuh8MbrMbX3okJOvkYBtvQZwpJFf+6EEag7ockJAY3m9xPE2p9D13MXrdH8B38xy92sUlTy8ZXGUJnvxJ1rC2R0L36I/9kPCB0wZds8Sric+udXH+RJwHdDXWEFctbbavt8dqRLQYF5BXKJDq9MdF9nAodY50xgXejJOFc6G2ciVkxxTh5SgRSA5Ua5TyQ/y+pEwJmxWal2ZnuX7YmvBxmISeViyFPjuk44m2T3hP3ixRZ7g8oZELA=--eUB6i34uh99QEI2f--/B2+Osp2gY7wUfEki3yt7w== \ No newline at end of file diff --git a/config/environments/development.rb b/config/environments/development.rb index 3d6b073..4382feb 100644 --- a/config/environments/development.rb +++ b/config/environments/development.rb @@ -62,4 +62,32 @@ # Uncomment if you wish to allow Action Cable access from any origin. # config.action_cable.disable_request_forgery_protection = true + config.action_mailer.delivery_method = :smtp + + config.action_mailer.smtp_settings = { + address: 'smtp.gmail.com', + port: 587, + domain: 'gmail.com', + user_name: Rails.application.credentials.dig(:gmail, :user_name), + password: Rails.application.credentials.dig(:gmail, :password), + authentication: 'plain', + # ssl: :true, + # tsl: :true, + enable_starttls_auto: true + } + + config.action_mailer.perform_deliveries = true + config.action_mailer.raise_delivery_errors = true + config.action_mailer.default :charset => "utf-8" + + + + + + + + + + + config.action_mailer.default_url_options = { host: 'localhost', port: 3000 } end diff --git a/config/initializers/cors.rb b/config/initializers/cors.rb index e5a82f1..6bd8a0c 100644 --- a/config/initializers/cors.rb +++ b/config/initializers/cors.rb @@ -5,12 +5,18 @@ # Read more: https://github.com/cyu/rack-cors -# Rails.application.config.middleware.insert_before 0, Rack::Cors do -# allow do -# origins "example.com" -# -# resource "*", -# headers: :any, -# methods: [:get, :post, :put, :patch, :delete, :options, :head] -# end -# end +# config/initializers/cors.rb +Rails.application.config.middleware.insert_before 0, Rack::Cors do + origins = [ + 'localhost:3000', 'localhost:3001', 'localhost:5000', + 'staging.xyz.com', 'www.xyz.com', + ].freeze + allow do + origins origins + resource( + '*', + headers: :any, + methods: [:get, :patch, :put, :delete, :post, :options, :show] + ) + end +end diff --git a/config/initializers/devise.rb b/config/initializers/devise.rb new file mode 100644 index 0000000..6830a38 --- /dev/null +++ b/config/initializers/devise.rb @@ -0,0 +1,324 @@ +# frozen_string_literal: true + +# Assuming you have not yet modified this file, each configuration option below +# is set to its default value. Note that some are commented out while others +# are not: uncommented lines are intended to protect your configuration from +# breaking changes in upgrades (i.e., in the event that future versions of +# Devise change the default values for those options). +# +# Use this hook to configure devise mailer, warden hooks and so forth. +# Many of these configuration options can be set straight in your model. +Devise.setup do |config| + # The secret key used by Devise. Devise uses this key to generate + # random tokens. Changing this key will render invalid all existing + # confirmation, reset password and unlock tokens in the database. + # Devise will use the `secret_key_base` as its `secret_key` + # by default. You can change it below and use your own secret key. + # config.secret_key = '10720104990e083970effbb7bd2c33d56bf8a6c3d7847a4911dda6debf45d6584fe1644a28437422120aa0f1dbb470e669753e875ea9ca3e9bac4bea234c8217' + + # ==> Controller configuration + # Configure the parent class to the devise controllers. + # config.parent_controller = 'DeviseController' + + # ==> Mailer Configuration + # Configure the e-mail address which will be shown in Devise::Mailer, + # note that it will be overwritten if you use your own mailer class + # with default "from" parameter. + config.mailer_sender = 'please-change-me-at-config-initializers-devise@example.com' + + # Configure the class responsible to send e-mails. + # config.mailer = 'Devise::Mailer' + + # Configure the parent class responsible to send e-mails. + # config.parent_mailer = 'ActionMailer::Base' + + # ==> ORM configuration + # Load and configure the ORM. Supports :active_record (default) and + # :mongoid (bson_ext recommended) by default. Other ORMs may be + # available as additional gems. + require 'devise/orm/active_record' + + # ==> Configuration for any authentication mechanism + # Configure which keys are used when authenticating a user. The default is + # just :email. You can configure it to use [:username, :subdomain], so for + # authenticating a user, both parameters are required. Remember that those + # parameters are used only when authenticating and not when retrieving from + # session. If you need permissions, you should implement that in a before filter. + # You can also supply a hash where the value is a boolean determining whether + # or not authentication should be aborted when the value is not present. + # config.authentication_keys = [:email] + + # Configure parameters from the request object used for authentication. Each entry + # given should be a request method and it will automatically be passed to the + # find_for_authentication method and considered in your model lookup. For instance, + # if you set :request_keys to [:subdomain], :subdomain will be used on authentication. + # The same considerations mentioned for authentication_keys also apply to request_keys. + # config.request_keys = [] + + # Configure which authentication keys should be case-insensitive. + # These keys will be downcased upon creating or modifying a user and when used + # to authenticate or find a user. Default is :email. + config.case_insensitive_keys = [:email] + + # Configure which authentication keys should have whitespace stripped. + # These keys will have whitespace before and after removed upon creating or + # modifying a user and when used to authenticate or find a user. Default is :email. + config.strip_whitespace_keys = [:email] + + # Tell if authentication through request.params is enabled. True by default. + # It can be set to an array that will enable params authentication only for the + # given strategies, for example, `config.params_authenticatable = [:database]` will + # enable it only for database (email + password) authentication. + # config.params_authenticatable = true + + # Tell if authentication through HTTP Auth is enabled. False by default. + # It can be set to an array that will enable http authentication only for the + # given strategies, for example, `config.http_authenticatable = [:database]` will + # enable it only for database authentication. + # For API-only applications to support authentication "out-of-the-box", you will likely want to + # enable this with :database unless you are using a custom strategy. + # The supported strategies are: + # :database = Support basic authentication with authentication key + password + # config.http_authenticatable = false + + # If 401 status code should be returned for AJAX requests. True by default. + # config.http_authenticatable_on_xhr = true + + # The realm used in Http Basic Authentication. 'Application' by default. + # config.http_authentication_realm = 'Application' + + # It will change confirmation, password recovery and other workflows + # to behave the same regardless if the e-mail provided was right or wrong. + # Does not affect registerable. + # config.paranoid = true + + # By default Devise will store the user in session. You can skip storage for + # particular strategies by setting this option. + # Notice that if you are skipping storage for all authentication paths, you + # may want to disable generating routes to Devise's sessions controller by + # passing skip: :sessions to `devise_for` in your config/routes.rb + config.skip_session_storage = [:http_auth] + + # By default, Devise cleans up the CSRF token on authentication to + # avoid CSRF token fixation attacks. This means that, when using AJAX + # requests for sign in and sign up, you need to get a new CSRF token + # from the server. You can disable this option at your own risk. + # config.clean_up_csrf_token_on_authentication = true + + # When false, Devise will not attempt to reload routes on eager load. + # This can reduce the time taken to boot the app but if your application + # requires the Devise mappings to be loaded during boot time the application + # won't boot properly. + # config.reload_routes = true + + # ==> Configuration for :database_authenticatable + # For bcrypt, this is the cost for hashing the password and defaults to 12. If + # using other algorithms, it sets how many times you want the password to be hashed. + # The number of stretches used for generating the hashed password are stored + # with the hashed password. This allows you to change the stretches without + # invalidating existing passwords. + # + # Limiting the stretches to just one in testing will increase the performance of + # your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use + # a value less than 10 in other environments. Note that, for bcrypt (the default + # algorithm), the cost increases exponentially with the number of stretches (e.g. + # a value of 20 is already extremely slow: approx. 60 seconds for 1 calculation). + config.stretches = Rails.env.test? ? 1 : 12 + + # Set up a pepper to generate the hashed password. + # config.pepper = '05f70292eed66a244befd3bb98eda6a12a0f61fed6abbeead77760c2f595c5ca7b6a826d5a9529bf6895a9edb272e032e33d771c26dfbfaf9a703032ffa689ba' + + # Send a notification to the original email when the user's email is changed. + # config.send_email_changed_notification = false + + # Send a notification email when the user's password is changed. + # config.send_password_change_notification = false + + # ==> Configuration for :confirmable + # A period that the user is allowed to access the website even without + # confirming their account. For instance, if set to 2.days, the user will be + # able to access the website for two days without confirming their account, + # access will be blocked just in the third day. + # You can also set it to nil, which will allow the user to access the website + # without confirming their account. + # Default is 0.days, meaning the user cannot access the website without + # confirming their account. + # config.allow_unconfirmed_access_for = 2.days + + # A period that the user is allowed to confirm their account before their + # token becomes invalid. For example, if set to 3.days, the user can confirm + # their account within 3 days after the mail was sent, but on the fourth day + # their account can't be confirmed with the token any more. + # Default is nil, meaning there is no restriction on how long a user can take + # before confirming their account. + # config.confirm_within = 3.days + + # If true, requires any email changes to be confirmed (exactly the same way as + # initial account confirmation) to be applied. Requires additional unconfirmed_email + # db field (see migrations). Until confirmed, new email is stored in + # unconfirmed_email column, and copied to email column on successful confirmation. + config.reconfirmable = true + + # Defines which key will be used when confirming an account + # config.confirmation_keys = [:email] + + # ==> Configuration for :rememberable + # The time the user will be remembered without asking for credentials again. + # config.remember_for = 2.weeks + + # Invalidates all the remember me tokens when the user signs out. + config.expire_all_remember_me_on_sign_out = true + + # If true, extends the user's remember period when remembered via cookie. + # config.extend_remember_period = false + + # Options to be passed to the created cookie. For instance, you can set + # secure: true in order to force SSL only cookies. + # config.rememberable_options = {} + + # ==> Configuration for :validatable + # Range for password length. + config.password_length = 6..128 + + # Email regex used to validate email formats. It simply asserts that + # one (and only one) @ exists in the given string. This is mainly + # to give user feedback and not to assert the e-mail validity. + config.email_regexp = /\A[^@\s]+@[^@\s]+\z/ + + # ==> Configuration for :timeoutable + # The time you want to timeout the user session without activity. After this + # time the user will be asked for credentials again. Default is 30 minutes. + # config.timeout_in = 30.minutes + + # ==> Configuration for :lockable + # Defines which strategy will be used to lock an account. + # :failed_attempts = Locks an account after a number of failed attempts to sign in. + # :none = No lock strategy. You should handle locking by yourself. + # config.lock_strategy = :failed_attempts + + # Defines which key will be used when locking and unlocking an account + # config.unlock_keys = [:email] + + # Defines which strategy will be used to unlock an account. + # :email = Sends an unlock link to the user email + # :time = Re-enables login after a certain amount of time (see :unlock_in below) + # :both = Enables both strategies + # :none = No unlock strategy. You should handle unlocking by yourself. + # config.unlock_strategy = :both + + # Number of authentication tries before locking an account if lock_strategy + # is failed attempts. + # config.maximum_attempts = 20 + + # Time interval to unlock the account if :time is enabled as unlock_strategy. + # config.unlock_in = 1.hour + + # Warn on the last attempt before the account is locked. + # config.last_attempt_warning = true + + # ==> Configuration for :recoverable + # + # Defines which key will be used when recovering the password for an account + # config.reset_password_keys = [:email] + + # Time interval you can reset your password with a reset password key. + # Don't put a too small interval or your users won't have the time to + # change their passwords. + config.reset_password_within = 6.hours + + # When set to false, does not sign a user in automatically after their password is + # reset. Defaults to true, so a user is signed in automatically after a reset. + # config.sign_in_after_reset_password = true + + # ==> Configuration for :encryptable + # Allow you to use another hashing or encryption algorithm besides bcrypt (default). + # You can use :sha1, :sha512 or algorithms from others authentication tools as + # :clearance_sha1, :authlogic_sha512 (then you should set stretches above to 20 + # for default behavior) and :restful_authentication_sha1 (then you should set + # stretches to 10, and copy REST_AUTH_SITE_KEY to pepper). + # + # Require the `devise-encryptable` gem when using anything other than bcrypt + # config.encryptor = :sha512 + + # ==> Scopes configuration + # Turn scoped views on. Before rendering "sessions/new", it will first check for + # "users/sessions/new". It's turned off by default because it's slower if you + # are using only default views. + # config.scoped_views = false + + # Configure the default scope given to Warden. By default it's the first + # devise role declared in your routes (usually :user). + # config.default_scope = :user + + # Set this configuration to false if you want /users/sign_out to sign out + # only the current scope. By default, Devise signs out all scopes. + # config.sign_out_all_scopes = true + + # ==> Navigation configuration + # Lists the formats that should be treated as navigational. Formats like + # :html, should redirect to the sign in page when the user does not have + # access, but formats like :xml or :json, should return 401. + # + # If you have any extra navigational formats, like :iphone or :mobile, you + # should add them to the navigational formats lists. + # + # The "*/*" below is required to match Internet Explorer requests. + # config.navigational_formats = ['*/*', :html] + + # The default HTTP method used to sign out a resource. Default is :delete. + config.sign_out_via = :delete + + # ==> OmniAuth + # Add a new OmniAuth provider. Check the wiki for more information on setting + # up on your models and hooks. + # config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo' + + # ==> Warden configuration + # If you want to use other strategies, that are not supported by Devise, or + # change the failure app, you can configure them inside the config.warden block. + # + # config.warden do |manager| + # manager.intercept_401 = false + # manager.default_strategies(scope: :user).unshift :some_external_strategy + # end + + # ==> Mountable engine configurations + # When using Devise inside an engine, let's call it `MyEngine`, and this engine + # is mountable, there are some extra configurations to be taken into account. + # The following options are available, assuming the engine is mounted as: + # + # mount MyEngine, at: '/my_engine' + # + # The router that invoked `devise_for`, in the example above, would be: + # config.router_name = :my_engine + # + # When using OmniAuth, Devise cannot automatically set OmniAuth path, + # so you need to do it manually. For the users scope, it would be: + # config.omniauth_path_prefix = '/my_engine/users/auth' + + # ==> Turbolinks configuration + # If your app is using Turbolinks, Turbolinks::Controller needs to be included to make redirection work correctly: + # + # ActiveSupport.on_load(:devise_failure_app) do + # include Turbolinks::Controller + # end + + # ==> Configuration for :registerable + + # When set to false, does not sign a user in automatically after their password is + # changed. Defaults to true, so a user is signed in automatically after changing a password. + # config.sign_in_after_change_password = true + config.navigational_formats = [] + + config.jwt do |jwt| + jwt.secret = Rails.application.credentials.devise_jwt_secret_key! + jwt.dispatch_requests = [ + ['POST', %r{^/login$}] + ] + jwt.revocation_requests = [ + ['DELETE', %r{^/logout$}] + ] + jwt.expiration_time = 60.minutes.to_i + jwt.aud_header = 'JWT_AUD' + end +end diff --git a/config/locales/devise.en.yml b/config/locales/devise.en.yml new file mode 100644 index 0000000..2a612b1 --- /dev/null +++ b/config/locales/devise.en.yml @@ -0,0 +1,69 @@ +# Additional translations at https://github.com/heartcombo/devise/wiki/I18n + +en: + devise: + confirmations: + confirmed: 'Your email address has been successfully confirmed.' + send_instructions: 'You will receive an email with instructions for how to confirm your email address in a few minutes.' + send_paranoid_instructions: 'If your email address exists in our database, you will receive an email with instructions for how to confirm your email address in a few minutes.' + failure: + already_authenticated: 'You are already signed in.' + inactive: 'Your account is not activated yet.' + invalid: 'Invalid %{authentication_keys} or password.' + locked: 'Your account is locked.' + last_attempt: 'You have one more attempt before your account is locked.' + not_found_in_database: 'Invalid %{authentication_keys} or password.' + timeout: 'Your session expired. Please sign in again to continue.' + unauthenticated: 'You need to sign in or sign up before continuing.' + unconfirmed: 'You have to confirm your email address before continuing.' + mailer: + confirmation_instructions: + subject: 'Confirmation instructions' + reset_password_instructions: + subject: 'Reset password instructions' + unlock_instructions: + subject: 'Unlock instructions' + email_changed: + subject: 'Email Changed' + password_change: + subject: 'Password Changed' + omniauth_callbacks: + failure: 'Could not authenticate you from %{kind} because "%{reason}".' + success: 'Successfully authenticated from %{kind} account.' + passwords: + no_token: "You can't access this page without coming from a password reset email. If you do come from a password reset email, please make sure you used the full URL provided." + send_instructions: 'You will receive an email with instructions on how to reset your password in a few minutes.' + send_paranoid_instructions: 'If your email address exists in our database, you will receive a password recovery link at your email address in a few minutes.' + updated: 'Your password has been changed successfully. You are now signed in.' + updated_not_active: 'Your password has been changed successfully.' + registrations: + destroyed: 'Bye! Your account has been successfully cancelled. We hope to see you again soon.' + signed_up: 'Welcome! You have signed up successfully.' + signed_up_but_inactive: 'You have signed up successfully. However, we could not sign you in because your account is not yet activated.' + signed_up_but_locked: 'You have signed up successfully. However, we could not sign you in because your account is locked.' + signed_up_but_unconfirmed: 'A message with a confirmation link has been sent to your email address. Please follow the link to activate your account.' + update_needs_confirmation: 'You updated your account successfully, but we need to verify your new email address. Please check your email and follow the confirmation link to confirm your new email address.' + updated: 'Your account has been updated successfully.' + updated_but_not_signed_in: 'Your account has been updated successfully, but since your password was changed, you need to sign in again.' + mentor: + signed_up_but_not_approved: 'You have signed up successfully but your account has not been approved by your administrator yet' + + sessions: + signed_in: 'Signed in successfully.' + signed_out: 'Signed out successfully.' + already_signed_out: 'Signed out successfully.' + unlocks: + send_instructions: 'You will receive an email with instructions for how to unlock your account in a few minutes.' + send_paranoid_instructions: 'If your account exists, you will receive an email with instructions for how to unlock it in a few minutes.' + unlocked: 'Your account has been unlocked successfully. Please sign in to continue.' + errors: + messages: + already_confirmed: 'was already confirmed, please try signing in' + confirmation_period_expired: 'needs to be confirmed within %{period}, please request a new one' + expired: 'has expired, please request a new one' + not_found: 'not found' + not_locked: 'was not locked' + not_saved: + one: '1 error prohibited this %{resource} from being saved:' + other: '%{count} errors prohibited this %{resource} from being saved:' + not_approved: 'Your account has not been approved by your administrator yet.' diff --git a/config/routes.rb b/config/routes.rb index 262ffd5..ff592d9 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,4 +1,16 @@ Rails.application.routes.draw do + devise_for :mentors,controllers: { + registrations: 'api/v1/mentors/registrations', + sessions: 'api/v1/mentors/sessions', + } + + devise_for :users,controllers: { + sessions: 'api/v1/users/sessions', + registrations: 'api/v1/users/registrations' + } + + get '/member-data', to: 'members#show' + get '/mentors-member', to: 'mentor_members#show' # Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html # Defines the root path route ("/") diff --git a/db/migrate/20220818151926_devise_create_users.rb b/db/migrate/20220818151926_devise_create_users.rb new file mode 100644 index 0000000..7a9a598 --- /dev/null +++ b/db/migrate/20220818151926_devise_create_users.rb @@ -0,0 +1,44 @@ +# frozen_string_literal: true + +class DeviseCreateUsers < ActiveRecord::Migration[7.0] + def change + create_table :users do |t| + ## Database authenticatable + t.string :email, null: false, default: "" + t.string :encrypted_password, null: false, default: "" + + ## Recoverable + t.string :reset_password_token + t.datetime :reset_password_sent_at + + ## Rememberable + t.datetime :remember_created_at + + ## Trackable + # t.integer :sign_in_count, default: 0, null: false + # t.datetime :current_sign_in_at + # t.datetime :last_sign_in_at + # t.string :current_sign_in_ip + # t.string :last_sign_in_ip + + ## Confirmable + # t.string :confirmation_token + # t.datetime :confirmed_at + # t.datetime :confirmation_sent_at + # t.string :unconfirmed_email # Only if using reconfirmable + + ## Lockable + # t.integer :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts + # t.string :unlock_token # Only if unlock strategy is :email or :both + # t.datetime :locked_at + + + t.timestamps null: false + end + + # add_index :users, :email, unique: true + add_index :users, :reset_password_token, unique: true + # add_index :users, :confirmation_token, unique: true + # add_index :users, :unlock_token, unique: true + end +end diff --git a/db/migrate/20220818153548_devise_create_mentors.rb b/db/migrate/20220818153548_devise_create_mentors.rb new file mode 100644 index 0000000..be67119 --- /dev/null +++ b/db/migrate/20220818153548_devise_create_mentors.rb @@ -0,0 +1,48 @@ +# frozen_string_literal: true + +class DeviseCreateMentors < ActiveRecord::Migration[7.0] + def change + create_table :mentors do |t| + ## Database authenticatable + + t.string :email, null: false, default: "" + t.string :encrypted_password, null: false, default: "" + + ## Recoverable + t.string :reset_password_token + t.datetime :reset_password_sent_at + + ## Rememberable + t.datetime :remember_created_at + + ## Trackable + # t.integer :sign_in_count, default: 0, null: false + # t.datetime :current_sign_in_at + # t.datetime :last_sign_in_at + # t.string :current_sign_in_ip + # t.string :last_sign_in_ip + + ## Confirmable + # t.string :confirmation_token + # t.datetime :confirmed_at + # t.datetime :confirmation_sent_at + # t.string :unconfirmed_email # Only if using reconfirmable + + ## Lockable + # t.integer :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts + # t.string :unlock_token # Only if unlock strategy is :email or :both + # t.datetime :locked_at + + t.string :bio + t.integer :specialization_id + t.string :name + + t.timestamps null: false + end + + add_index :mentors, :email, unique: true + add_index :mentors, :reset_password_token, unique: true + # add_index :mentors, :confirmation_token, unique: true + # add_index :mentors, :unlock_token, unique: true + end +end diff --git a/db/migrate/20220818201247_create_jwt_denylists.rb b/db/migrate/20220818201247_create_jwt_denylists.rb new file mode 100644 index 0000000..5fa1a0c --- /dev/null +++ b/db/migrate/20220818201247_create_jwt_denylists.rb @@ -0,0 +1,11 @@ +class CreateJwtDenylists < ActiveRecord::Migration[7.0] + def change + create_table :jwt_denylists do |t| + t.string :jti, null: false + t.datetime :exp, null: false + t.timestamps + end + + add_index :jwt_denylists, :jti + end +end diff --git a/db/migrate/20220818202141_create_allow_listed_jwts.rb b/db/migrate/20220818202141_create_allow_listed_jwts.rb new file mode 100644 index 0000000..6b0bafe --- /dev/null +++ b/db/migrate/20220818202141_create_allow_listed_jwts.rb @@ -0,0 +1,17 @@ +class CreateAllowListedJwts < ActiveRecord::Migration[7.0] + def change + create_table :allowlisted_jwts do |t| + t.string :jti, null: false + t.string :aud + t.datetime :exp, null: false + t.string :remote_ip + t.string :browser_data + t.string :os_data + t.string :device_data + t.timestamps null: false + end + + add_reference :allowlisted_jwts, :user, foreign_key: {to_table: :users, on_delete: :cascade} + add_index :allowlisted_jwts, :jti, unique: true + end +end diff --git a/db/migrate/20220819020707_add_username_to_users.rb b/db/migrate/20220819020707_add_username_to_users.rb new file mode 100644 index 0000000..d9f2888 --- /dev/null +++ b/db/migrate/20220819020707_add_username_to_users.rb @@ -0,0 +1,5 @@ +class AddUsernameToUsers < ActiveRecord::Migration[7.0] + def change + add_column :users, :user_name, :string, null: false, default: "" + end +end diff --git a/db/migrate/20220820185203_create_allowlisted_mentors_jwts.rb b/db/migrate/20220820185203_create_allowlisted_mentors_jwts.rb new file mode 100644 index 0000000..745193b --- /dev/null +++ b/db/migrate/20220820185203_create_allowlisted_mentors_jwts.rb @@ -0,0 +1,17 @@ +class CreateAllowlistedMentorsJwts < ActiveRecord::Migration[7.0] + def change + create_table :allowlisted_mentors_jwts do |t| + t.string :jti, null: false + t.string :aud + t.datetime :exp, null: false + t.string :remote_ip + t.string :browser_data + t.string :os_data + t.string :device_data + t.timestamps + end + + add_reference :allowlisted_mentors_jwts, :mentor, foreign_key: {to_table: :mentors, on_delete: :cascade} + add_index :allowlisted_mentors_jwts, :jti, unique: true + end +end diff --git a/db/migrate/20220820201005_add_approved_to_mentor.rb b/db/migrate/20220820201005_add_approved_to_mentor.rb new file mode 100644 index 0000000..ff94ff2 --- /dev/null +++ b/db/migrate/20220820201005_add_approved_to_mentor.rb @@ -0,0 +1,11 @@ +class AddApprovedToMentor < ActiveRecord::Migration[7.0] + def change + add_column :mentors, :approved, :boolean, null: false, default: false + add_index :mentors, :approved + end + + def self.down + remove_column :mentors, :approved + remove_index :mentors, :approved + end +end diff --git a/db/migrate/20220820204348_add_role_to_user.rb b/db/migrate/20220820204348_add_role_to_user.rb new file mode 100644 index 0000000..7330787 --- /dev/null +++ b/db/migrate/20220820204348_add_role_to_user.rb @@ -0,0 +1,5 @@ +class AddRoleToUser < ActiveRecord::Migration[7.0] + def change + add_column :users, :role, :string, null: false, default: "user" + end +end diff --git a/db/schema.rb b/db/schema.rb index b783f98..d7bb99b 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -10,8 +10,78 @@ # # It's strongly recommended that you check this file into your version control system. -ActiveRecord::Schema[7.0].define(version: 0) do +ActiveRecord::Schema[7.0].define(version: 2022_08_20_204348) do # These are extensions that must be enabled in order to support this database enable_extension "plpgsql" + create_table "allowlisted_jwts", force: :cascade do |t| + t.string "jti", null: false + t.string "aud", null: false + t.datetime "exp", null: false + t.string "remote_ip" + t.string "browser_data" + t.string "os_data" + t.string "device_data" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.bigint "user_id" + t.index ["jti"], name: "index_allowlisted_jwts_on_jti", unique: true + t.index ["user_id"], name: "index_allowlisted_jwts_on_user_id" + end + + create_table "allowlisted_mentors_jwts", force: :cascade do |t| + t.string "jti", null: false + t.string "aud" + t.datetime "exp", null: false + t.string "remote_ip" + t.string "browser_data" + t.string "os_data" + t.string "device_data" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.bigint "mentor_id" + t.index ["jti"], name: "index_allowlisted_mentors_jwts_on_jti", unique: true + t.index ["mentor_id"], name: "index_allowlisted_mentors_jwts_on_mentor_id" + end + + create_table "jwt_denylists", force: :cascade do |t| + t.string "jti", null: false + t.datetime "exp", null: false + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index ["jti"], name: "index_jwt_denylists_on_jti" + end + + create_table "mentors", force: :cascade do |t| + t.string "email", default: "", null: false + t.string "encrypted_password", default: "", null: false + t.string "reset_password_token" + t.datetime "reset_password_sent_at" + t.datetime "remember_created_at" + t.string "bio" + t.integer "specialization_id" + t.string "name" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.boolean "approved", default: false, null: false + t.index ["approved"], name: "index_mentors_on_approved" + t.index ["email"], name: "index_mentors_on_email", unique: true + t.index ["reset_password_token"], name: "index_mentors_on_reset_password_token", unique: true + end + + create_table "users", force: :cascade do |t| + t.string "email", default: "", null: false + t.string "encrypted_password", default: "", null: false + t.string "reset_password_token" + t.datetime "reset_password_sent_at" + t.datetime "remember_created_at" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.string "user_name", default: "", null: false + t.string "role", default: "user", null: false + t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true + end + + add_foreign_key "allowlisted_jwts", "users", on_delete: :cascade + add_foreign_key "allowlisted_mentors_jwts", "mentors", on_delete: :cascade end diff --git a/spec/mailers/admin_mailer_spec.rb b/spec/mailers/admin_mailer_spec.rb new file mode 100644 index 0000000..9264c50 --- /dev/null +++ b/spec/mailers/admin_mailer_spec.rb @@ -0,0 +1,5 @@ +require 'rails_helper' + +RSpec.describe AdminMailer, type: :mailer do + pending "add some examples to (or delete) #{__FILE__}" +end diff --git a/spec/mailers/previews/admin_mailer_preview.rb b/spec/mailers/previews/admin_mailer_preview.rb new file mode 100644 index 0000000..b3f5edd --- /dev/null +++ b/spec/mailers/previews/admin_mailer_preview.rb @@ -0,0 +1,3 @@ +# Preview all emails at http://localhost:3000/rails/mailers/admin_mailer +class AdminMailerPreview < ActionMailer::Preview +end diff --git a/spec/models/allowlisted_mentors_jwt_spec.rb b/spec/models/allowlisted_mentors_jwt_spec.rb new file mode 100644 index 0000000..47e70bc --- /dev/null +++ b/spec/models/allowlisted_mentors_jwt_spec.rb @@ -0,0 +1,5 @@ +require 'rails_helper' + +RSpec.describe AllowlistedMentorsJwt, type: :model do + pending "add some examples to (or delete) #{__FILE__}" +end diff --git a/spec/rails_helper.rb b/spec/rails_helper.rb new file mode 100644 index 0000000..34fa375 --- /dev/null +++ b/spec/rails_helper.rb @@ -0,0 +1,64 @@ +# This file is copied to spec/ when you run 'rails generate rspec:install' +require 'spec_helper' +ENV['RAILS_ENV'] ||= 'test' +require_relative '../config/environment' +# Prevent database truncation if the environment is production +abort('The Rails environment is running in production mode!') if Rails.env.production? +require 'rspec/rails' +# Add additional requires below this line. Rails is not loaded until this point! + +# Requires supporting ruby files with custom matchers and macros, etc, in +# spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are +# run as spec files by default. This means that files in spec/support that end +# in _spec.rb will both be required and run as specs, causing the specs to be +# run twice. It is recommended that you do not name files matching this glob to +# end with _spec.rb. You can configure this pattern with the --pattern +# option on the command line or in ~/.rspec, .rspec or `.rspec-local`. +# +# The following line is provided for convenience purposes. It has the downside +# of increasing the boot-up time by auto-requiring all files in the support +# directory. Alternatively, in the individual `*_spec.rb` files, manually +# require only the support files necessary. +# +# Dir[Rails.root.join('spec', 'support', '**', '*.rb')].sort.each { |f| require f } + +# Checks for pending migrations and applies them before tests are run. +# If you are not using ActiveRecord, you can remove these lines. +begin + ActiveRecord::Migration.maintain_test_schema! +rescue ActiveRecord::PendingMigrationError => e + puts e.to_s.strip + exit 1 +end +RSpec.configure do |config| + # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures + config.fixture_path = "#{::Rails.root}/spec/fixtures" + + # If you're not using ActiveRecord, or you'd prefer not to run each of your + # examples within a transaction, remove the following line or assign false + # instead of true. + config.use_transactional_fixtures = true + + # You can uncomment this line to turn off ActiveRecord support entirely. + # config.use_active_record = false + + # RSpec Rails can automatically mix in different behaviours to your tests + # based on their file location, for example enabling you to call `get` and + # `post` in specs under `spec/controllers`. + # + # You can disable this behaviour by removing the line below, and instead + # explicitly tag your specs with their type, e.g.: + # + # RSpec.describe UsersController, type: :controller do + # # ... + # end + # + # The different available types are documented in the features, such as in + # https://relishapp.com/rspec/rspec-rails/docs + config.infer_spec_type_from_file_location! + + # Filter lines from Rails gems in backtraces. + config.filter_rails_from_backtrace! + # arbitrary gems may also be filtered via: + # config.filter_gems_from_backtrace("gem name") +end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb new file mode 100644 index 0000000..d0cef33 --- /dev/null +++ b/spec/spec_helper.rb @@ -0,0 +1,92 @@ +# This file was generated by the `rails generate rspec:install` command. Conventionally, all +# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. +# The generated `.rspec` file contains `--require spec_helper` which will cause +# this file to always be loaded, without a need to explicitly require it in any +# files. +# +# Given that it is always loaded, you are encouraged to keep this file as +# light-weight as possible. Requiring heavyweight dependencies from this file +# will add to the boot time of your test suite on EVERY test run, even for an +# individual file that may not need all of that loaded. Instead, consider making +# a separate helper file that requires the additional dependencies and performs +# the additional setup, and require it from the spec files that actually need +# it. +# +# See https://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration +RSpec.configure do |config| + # rspec-expectations config goes here. You can use an alternate + # assertion/expectation library such as wrong or the stdlib/minitest + # assertions if you prefer. + config.expect_with :rspec do |expectations| + # This option will default to `true` in RSpec 4. It makes the `description` + # and `failure_message` of custom matchers include text for helper methods + # defined using `chain`, e.g.: + # be_bigger_than(2).and_smaller_than(4).description + # # => "be bigger than 2 and smaller than 4" + # ...rather than: + # # => "be bigger than 2" + expectations.include_chain_clauses_in_custom_matcher_descriptions = true + end + + # rspec-mocks config goes here. You can use an alternate test double + # library (such as bogus or mocha) by changing the `mock_with` option here. + config.mock_with :rspec do |mocks| + # Prevents you from mocking or stubbing a method that does not exist on + # a real object. This is generally recommended, and will default to + # `true` in RSpec 4. + mocks.verify_partial_doubles = true + end + + # This option will default to `:apply_to_host_groups` in RSpec 4 (and will + # have no way to turn it off -- the option exists only for backwards + # compatibility in RSpec 3). It causes shared context metadata to be + # inherited by the metadata hash of host groups and examples, rather than + # triggering implicit auto-inclusion in groups with matching metadata. + config.shared_context_metadata_behavior = :apply_to_host_groups + + # The settings below are suggested to provide a good initial experience + # with RSpec, but feel free to customize to your heart's content. + # # This allows you to limit a spec run to individual examples or groups + # # you care about by tagging them with `:focus` metadata. When nothing + # # is tagged with `:focus`, all examples get run. RSpec also provides + # # aliases for `it`, `describe`, and `context` that include `:focus` + # # metadata: `fit`, `fdescribe` and `fcontext`, respectively. + # config.filter_run_when_matching :focus + # + # # Allows RSpec to persist some state between runs in order to support + # # the `--only-failures` and `--next-failure` CLI options. We recommend + # # you configure your source control system to ignore this file. + # config.example_status_persistence_file_path = "spec/examples.txt" + # + # # Limits the available syntax to the non-monkey patched syntax that is + # # recommended. For more details, see: + # # https://relishapp.com/rspec/rspec-core/docs/configuration/zero-monkey-patching-mode + # config.disable_monkey_patching! + # + # # Many RSpec users commonly either run the entire suite or an individual + # # file, and it's useful to allow more verbose output when running an + # # individual spec file. + # if config.files_to_run.one? + # # Use the documentation formatter for detailed output, + # # unless a formatter has already been configured + # # (e.g. via a command-line flag). + # config.default_formatter = "doc" + # end + # + # # Print the 10 slowest examples and example groups at the + # # end of the spec run, to help surface which specs are running + # # particularly slow. + # config.profile_examples = 10 + # + # # Run specs in random order to surface order dependencies. If you find an + # # order dependency and want to debug it, you can fix the order by providing + # # the seed, which is printed after each run. + # # --seed 1234 + # config.order = :random + # + # # Seed global randomization in this process using the `--seed` CLI option. + # # Setting this allows you to use `--seed` to deterministically reproduce + # # test failures related to randomization by passing the same `--seed` value + # # as the one that triggered the failure. + # Kernel.srand config.seed +end diff --git a/test/channels/application_cable/connection_test.rb b/test/channels/application_cable/connection_test.rb index 800405f..d05dbd2 100644 --- a/test/channels/application_cable/connection_test.rb +++ b/test/channels/application_cable/connection_test.rb @@ -1,4 +1,4 @@ -require "test_helper" +require 'test_helper' class ApplicationCable::ConnectionTest < ActionCable::Connection::TestCase # test "connects with cookies" do diff --git a/test/fixtures/allow_listed_jwts.yml b/test/fixtures/allow_listed_jwts.yml new file mode 100644 index 0000000..d7a3329 --- /dev/null +++ b/test/fixtures/allow_listed_jwts.yml @@ -0,0 +1,11 @@ +# Read about fixtures at https://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html + +# This model initially had no columns defined. If you add columns to the +# model remove the "{}" from the fixture names and add the columns immediately +# below each fixture, per the syntax in the comments below +# +one: {} +# column: value +# +two: {} +# column: value diff --git a/test/fixtures/jwt_denylists.yml b/test/fixtures/jwt_denylists.yml new file mode 100644 index 0000000..d7a3329 --- /dev/null +++ b/test/fixtures/jwt_denylists.yml @@ -0,0 +1,11 @@ +# Read about fixtures at https://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html + +# This model initially had no columns defined. If you add columns to the +# model remove the "{}" from the fixture names and add the columns immediately +# below each fixture, per the syntax in the comments below +# +one: {} +# column: value +# +two: {} +# column: value diff --git a/test/fixtures/mentors.yml b/test/fixtures/mentors.yml new file mode 100644 index 0000000..d7a3329 --- /dev/null +++ b/test/fixtures/mentors.yml @@ -0,0 +1,11 @@ +# Read about fixtures at https://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html + +# This model initially had no columns defined. If you add columns to the +# model remove the "{}" from the fixture names and add the columns immediately +# below each fixture, per the syntax in the comments below +# +one: {} +# column: value +# +two: {} +# column: value diff --git a/test/fixtures/users.yml b/test/fixtures/users.yml new file mode 100644 index 0000000..d7a3329 --- /dev/null +++ b/test/fixtures/users.yml @@ -0,0 +1,11 @@ +# Read about fixtures at https://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html + +# This model initially had no columns defined. If you add columns to the +# model remove the "{}" from the fixture names and add the columns immediately +# below each fixture, per the syntax in the comments below +# +one: {} +# column: value +# +two: {} +# column: value diff --git a/test/models/allow_listed_jwt_test.rb b/test/models/allow_listed_jwt_test.rb new file mode 100644 index 0000000..39cc330 --- /dev/null +++ b/test/models/allow_listed_jwt_test.rb @@ -0,0 +1,7 @@ +require 'test_helper' + +class AllowListedJwtTest < ActiveSupport::TestCase + # test "the truth" do + # assert true + # end +end diff --git a/test/models/jwt_denylist_test.rb b/test/models/jwt_denylist_test.rb new file mode 100644 index 0000000..46affce --- /dev/null +++ b/test/models/jwt_denylist_test.rb @@ -0,0 +1,7 @@ +require 'test_helper' + +class JwtDenylistTest < ActiveSupport::TestCase + # test "the truth" do + # assert true + # end +end diff --git a/test/models/mentor_test.rb b/test/models/mentor_test.rb new file mode 100644 index 0000000..03d403f --- /dev/null +++ b/test/models/mentor_test.rb @@ -0,0 +1,7 @@ +require 'test_helper' + +class MentorTest < ActiveSupport::TestCase + # test "the truth" do + # assert true + # end +end diff --git a/test/models/user_test.rb b/test/models/user_test.rb new file mode 100644 index 0000000..82f61e0 --- /dev/null +++ b/test/models/user_test.rb @@ -0,0 +1,7 @@ +require 'test_helper' + +class UserTest < ActiveSupport::TestCase + # test "the truth" do + # assert true + # end +end diff --git a/test/test_helper.rb b/test/test_helper.rb index d713e37..d5300f8 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -1,6 +1,6 @@ -ENV["RAILS_ENV"] ||= "test" -require_relative "../config/environment" -require "rails/test_help" +ENV['RAILS_ENV'] ||= 'test' +require_relative '../config/environment' +require 'rails/test_help' class ActiveSupport::TestCase # Run tests in parallel with specified workers