diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..31eeee0 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,7 @@ +# See https://git-scm.com/docs/gitattributes for more about git attribute files. + +# Mark the database schema as having been generated. +db/schema.rb linguist-generated + +# Mark any vendored files as having been vendored. +vendor/* linguist-vendored diff --git a/.rubocop.yml b/.rubocop.yml new file mode 100644 index 0000000..07176e9 --- /dev/null +++ b/.rubocop.yml @@ -0,0 +1,19 @@ +AllCops: + TargetRubyVersion: 3.0.2 + Exclude: + - 'config.ru' + - 'Rakefile' + - 'config/**/*' + - 'bin/*' + - 'test/**/*' + - 'spec/**/' + - 'db/**/*' + - 'api_test.rb' + + NewCops: enable + +Style/Documentation: + Enabled: false + +Bundler/OrderedGems: + Enabled: false diff --git a/.ruby-version b/.ruby-version new file mode 100644 index 0000000..e76033b --- /dev/null +++ b/.ruby-version @@ -0,0 +1 @@ +ruby-3.0.3 diff --git a/Gemfile b/Gemfile new file mode 100644 index 0000000..c812703 --- /dev/null +++ b/Gemfile @@ -0,0 +1,28 @@ +# frozen_string_literal: true + +source 'https://rubygems.org' +git_source(:github) { |repo| "https://github.com/#{repo}.git" } + +ruby '3.0.3' + +gem 'rails', '~> 7.0.0' +gem 'puma', '~> 5.0' +gem 'bcrypt', '~> 3.1.7' +gem 'tzinfo-data', platforms: %i[mingw mswin x64_mingw jruby] +gem 'bootsnap', require: false +gem 'jwt', '~> 2.3' +gem 'pg', '~> 1.2' +gem 'rack-cors', '~> 1.1' +gem 'will_paginate', '~> 3.3' +gem 'active_model_serializers', '~> 0.10.13' + +group :development, :test do + gem 'debug', platforms: %i[mri mingw x64_mingw] + gem 'rdoc' + gem 'rspec-rails' +end + +group :development do + gem 'faker', '~> 2.19' + gem 'sqlite3', '~> 1.4' +end diff --git a/Gemfile.lock b/Gemfile.lock new file mode 100644 index 0000000..a30aa05 --- /dev/null +++ b/Gemfile.lock @@ -0,0 +1,224 @@ +GEM + remote: https://rubygems.org/ + specs: + actioncable (7.0.1) + actionpack (= 7.0.1) + activesupport (= 7.0.1) + nio4r (~> 2.0) + websocket-driver (>= 0.6.1) + actionmailbox (7.0.1) + actionpack (= 7.0.1) + activejob (= 7.0.1) + activerecord (= 7.0.1) + activestorage (= 7.0.1) + activesupport (= 7.0.1) + mail (>= 2.7.1) + net-imap + net-pop + net-smtp + actionmailer (7.0.1) + actionpack (= 7.0.1) + actionview (= 7.0.1) + activejob (= 7.0.1) + activesupport (= 7.0.1) + mail (~> 2.5, >= 2.5.4) + net-imap + net-pop + net-smtp + rails-dom-testing (~> 2.0) + actionpack (7.0.1) + actionview (= 7.0.1) + activesupport (= 7.0.1) + rack (~> 2.0, >= 2.2.0) + rack-test (>= 0.6.3) + rails-dom-testing (~> 2.0) + rails-html-sanitizer (~> 1.0, >= 1.2.0) + actiontext (7.0.1) + actionpack (= 7.0.1) + activerecord (= 7.0.1) + activestorage (= 7.0.1) + activesupport (= 7.0.1) + globalid (>= 0.6.0) + nokogiri (>= 1.8.5) + actionview (7.0.1) + activesupport (= 7.0.1) + builder (~> 3.1) + erubi (~> 1.4) + rails-dom-testing (~> 2.0) + rails-html-sanitizer (~> 1.1, >= 1.2.0) + active_model_serializers (0.10.13) + actionpack (>= 4.1, < 7.1) + activemodel (>= 4.1, < 7.1) + case_transform (>= 0.2) + jsonapi-renderer (>= 0.1.1.beta1, < 0.3) + activejob (7.0.1) + activesupport (= 7.0.1) + globalid (>= 0.3.6) + activemodel (7.0.1) + activesupport (= 7.0.1) + activerecord (7.0.1) + activemodel (= 7.0.1) + activesupport (= 7.0.1) + activestorage (7.0.1) + actionpack (= 7.0.1) + activejob (= 7.0.1) + activerecord (= 7.0.1) + activesupport (= 7.0.1) + marcel (~> 1.0) + mini_mime (>= 1.1.0) + activesupport (7.0.1) + concurrent-ruby (~> 1.0, >= 1.0.2) + i18n (>= 1.6, < 2) + minitest (>= 5.1) + tzinfo (~> 2.0) + bcrypt (3.1.16) + bootsnap (1.10.1) + msgpack (~> 1.2) + builder (3.2.4) + case_transform (0.2) + activesupport + concurrent-ruby (1.1.9) + crass (1.0.6) + debug (1.4.0) + irb (>= 1.3.6) + reline (>= 0.2.7) + diff-lcs (1.5.0) + digest (3.1.0) + erubi (1.10.0) + faker (2.19.0) + i18n (>= 1.6, < 2) + globalid (1.0.0) + activesupport (>= 5.0) + i18n (1.8.11) + concurrent-ruby (~> 1.0) + io-console (0.5.11) + io-wait (0.2.1) + irb (1.4.1) + reline (>= 0.3.0) + jsonapi-renderer (0.2.2) + jwt (2.3.0) + loofah (2.13.0) + crass (~> 1.0.2) + nokogiri (>= 1.5.9) + mail (2.7.1) + mini_mime (>= 0.1.1) + marcel (1.0.2) + method_source (1.0.0) + mini_mime (1.1.2) + minitest (5.15.0) + msgpack (1.4.2) + net-imap (0.2.3) + digest + net-protocol + strscan + net-pop (0.1.1) + digest + net-protocol + timeout + net-protocol (0.1.2) + io-wait + timeout + net-smtp (0.3.1) + digest + net-protocol + timeout + nio4r (2.5.8) + nokogiri (1.13.1-x86_64-linux) + racc (~> 1.4) + pg (1.2.3) + psych (4.0.3) + stringio + puma (5.5.2) + nio4r (~> 2.0) + racc (1.6.0) + rack (2.2.3) + rack-cors (1.1.1) + rack (>= 2.0.0) + rack-test (1.1.0) + rack (>= 1.0, < 3) + rails (7.0.1) + actioncable (= 7.0.1) + actionmailbox (= 7.0.1) + actionmailer (= 7.0.1) + actionpack (= 7.0.1) + actiontext (= 7.0.1) + actionview (= 7.0.1) + activejob (= 7.0.1) + activemodel (= 7.0.1) + activerecord (= 7.0.1) + activestorage (= 7.0.1) + activesupport (= 7.0.1) + bundler (>= 1.15.0) + railties (= 7.0.1) + rails-dom-testing (2.0.3) + activesupport (>= 4.2.0) + nokogiri (>= 1.6) + rails-html-sanitizer (1.4.2) + loofah (~> 2.3) + railties (7.0.1) + actionpack (= 7.0.1) + activesupport (= 7.0.1) + method_source + rake (>= 12.2) + thor (~> 1.0) + zeitwerk (~> 2.5) + rake (13.0.6) + rdoc (6.4.0) + psych (>= 4.0.0) + reline (0.3.1) + io-console (~> 0.5) + rspec-core (3.10.1) + rspec-support (~> 3.10.0) + rspec-expectations (3.10.2) + diff-lcs (>= 1.2.0, < 2.0) + rspec-support (~> 3.10.0) + rspec-mocks (3.10.2) + diff-lcs (>= 1.2.0, < 2.0) + rspec-support (~> 3.10.0) + rspec-rails (5.0.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.10.3) + sqlite3 (1.4.2) + stringio (3.0.1) + strscan (3.0.1) + thor (1.2.1) + timeout (0.2.0) + tzinfo (2.0.4) + concurrent-ruby (~> 1.0) + websocket-driver (0.7.5) + websocket-extensions (>= 0.1.0) + websocket-extensions (0.1.5) + will_paginate (3.3.1) + zeitwerk (2.5.3) + +PLATFORMS + x86_64-linux + +DEPENDENCIES + active_model_serializers (~> 0.10.13) + bcrypt (~> 3.1.7) + bootsnap + debug + faker (~> 2.19) + jwt (~> 2.3) + pg (~> 1.2) + puma (~> 5.0) + rack-cors (~> 1.1) + rails (~> 7.0.0) + rdoc + rspec-rails + sqlite3 (~> 1.4) + tzinfo-data + will_paginate (~> 3.3) + +RUBY VERSION + ruby 3.0.3p157 + +BUNDLED WITH + 2.2.33 diff --git a/README.md b/README.md new file mode 100644 index 0000000..327a301 --- /dev/null +++ b/README.md @@ -0,0 +1,70 @@ +# Rails simple blog app + +## Api only + + +``` + Ruby 3.0.+ + Rails 7 +``` + +#### Clone the repo into your local machine + + +* Install Gems + +``` +bundle install +``` + +* Migrate the database + +``` +rake db:migrate +``` + +* Run the server + +``` +rails s +``` + +* Open a new Terminal tab and test the apis + +## APIS +``` +| API | METHOD | DESCRIPTION +============================|===========|================== +| /register | POST | create new account +| /login | POST | get authorization token +| /users | DELETE | delete account + +| /posts | GET | get all posts +| /posts | POST | create new post +| /posts/:id | PATCH/PUT | update post content +| /posts/:id | DELETE | delete post + +| /posts/:post_id/comments | GET | get all comments of the post +| /posts/:post_id/comments | POST | submit comment for post +| /comments/:id | PATCH/PUT | update comment +| /comments/:id | DELETE | delete comment +------------------------------------------------------------------------- +``` + +### APis and Params +``` +| API | PARAMS +============================|============================= +| /register | user: { first_name, last_name, email, password, password_confirmation } +| /login | user: { email, password } +| /users | confirmation_password + +| /posts | post: { title, content }, title is optional +| /posts/:id | post: { content } + +| /posts/:post_id/comments | commment: { content } +``` + +Check out [test.sh](api_test.sh) or [test.rb](test.rb) file. + +**NB:** You need to pass authorization token through header to do **post**, **patch** and **delete** operations. Get(read) operation does not need authorization token. diff --git a/Rakefile b/Rakefile new file mode 100644 index 0000000..e85f913 --- /dev/null +++ b/Rakefile @@ -0,0 +1,6 @@ +# Add your own tasks in files placed in lib/tasks ending in .rake, +# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. + +require_relative 'config/application' + +Rails.application.load_tasks diff --git a/api_test.rb b/api_test.rb new file mode 100644 index 0000000..7bdd3ce --- /dev/null +++ b/api_test.rb @@ -0,0 +1,3 @@ +require 'faraday' + +# unfinished diff --git a/api_test.sh b/api_test.sh new file mode 100755 index 0000000..7b4501a --- /dev/null +++ b/api_test.sh @@ -0,0 +1,68 @@ +#!/bin/bash + +## Registration + +# curl -H "Content-type: application/json" \ +# -X POST \ +# -d ' {"user":{"first_name":"Joh","email":"john@gmail.com","password":"123456789"}} ' \ +# http://localhost:3000/register && echo + +## Login +# +# curl -H "Content-type: application/json" \ +# -X POST \ +# -d ' {"user":{"email":"john@gmail.com","password":"123456789"}} ' \ +# http://localhost:3000/login && echo + +## DELETE Account +# curl -X DELETE \ +# -H "Content-type: application/json" \ +# -H "Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.eyJlbWFpbCI6ImpvaG5AZ21haWwuY29tIiwiZXhwIjoxNjQxMTM5MjY5fQ.31IpN1srlZgRJmgGzMNIK_5Bhah0qURki-z1raZ5w9Y" \ +# -d '{"confirmation":{"password":"123456789"}} ' \ +# http://localhost:3000/users && echo + +## Posts + +### New post +# curl -H "Content-type: application/json" \ +# -H "Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.eyJlbWFpbCI6ImpvaG5AZ21haWwuY29tIiwiZXhwIjoxNjQxMzk3NTE0fQ.nfxmyMz2MxqZlQkrrLf-ke6pzH0zgLaKaZxTJ-l1ajI" \ +# -X POST \ +# -d ' {"post":{"title":"hello world","content":"THis is hello world post"}} ' \ +# http://localhost:3000/posts && echo + +### Get posts +curl -H "Content-type: application/json" \ + -X GET \ + -d ' {"p":"1"} ' \ + http://localhost:3000/posts && echo + +### GET single post +# curl -H "Content-type: application/json" \ +# http://localhost:3000/posts/9 && echo + +## Delete post +# curl -H "Content-type: application/json" \ +# -H "Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.eyJlbWFpbCI6ImpvaG5AZ21haWwuY29tIiwiZXhwIjoxNjQxMTQxMjE1fQ.zIB2TdBP3q60XEPh0wFyxCqIGQyFz6ETuNBadd6vBcI" \ +# -X DELETE \ +# http://localhost:3000/posts/9 && echo + +# Comments +# new comment +# curl -H "Content-type: application/json" \ +# -H "Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.eyJlbWFpbCI6ImpvaG5AZ21haWwuY29tIiwiZXhwIjoxNjQxMTQxMjE1fQ.zIB2TdBP3q60XEPh0wFyxCqIGQyFz6ETuNBadd6vBcI" \ +# -X POST \ +# -d ' {"comment":{"content":"THis is test comment"}} ' \ +# http://localhost:3000/posts/7/comments && echo + +# comments +# curl -H "Content-type: application/json" \ +# http://localhost:3000/posts/7/comments + +# single comment +# curl -H "Content-type: application/json" \ +# http://localhost:3000/comments/2 + +# delete +# curl -H "Content-type: application/json" \ +# -H "Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.eyJlbWFpbCI6ImpvaG5AZ21haWwuY29tIiwiZXhwIjoxNjQxMTQxMjE1fQ.zIB2TdBP3q60XEPh0wFyxCqIGQyFz6ETuNBadd6vBcI" \ +# -X DELETE http://localhost:3000/comments/2 && echo diff --git a/app/channels/application_cable/channel.rb b/app/channels/application_cable/channel.rb new file mode 100644 index 0000000..9aec230 --- /dev/null +++ b/app/channels/application_cable/channel.rb @@ -0,0 +1,6 @@ +# frozen_string_literal: true + +module ApplicationCable + class Channel < ActionCable::Channel::Base + end +end diff --git a/app/channels/application_cable/connection.rb b/app/channels/application_cable/connection.rb new file mode 100644 index 0000000..8d6c2a1 --- /dev/null +++ b/app/channels/application_cable/connection.rb @@ -0,0 +1,6 @@ +# frozen_string_literal: true + +module ApplicationCable + class Connection < ActionCable::Connection::Base + end +end diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb new file mode 100644 index 0000000..f8b5401 --- /dev/null +++ b/app/controllers/application_controller.rb @@ -0,0 +1,6 @@ +# frozen_string_literal: true + +class ApplicationController < ActionController::API + include ApplicationConcern + include ExceptionHandler +end diff --git a/app/controllers/authentication_controller.rb b/app/controllers/authentication_controller.rb new file mode 100644 index 0000000..cc2fea8 --- /dev/null +++ b/app/controllers/authentication_controller.rb @@ -0,0 +1,21 @@ +# frozen_string_literal: true + +class AuthenticationController < ApplicationController + skip_before_action :authorize_api_request! + + # POST /login or POST / + def create + token = AuthenticateUser.new(login_params).call + if token.present? + render json: { authorization: token } + else + render_error_response 'Invalid data', :unauthorized + end + end + + private + + def login_params + params.require(:user).permit(:email, :password) + end +end diff --git a/app/controllers/comments_controller.rb b/app/controllers/comments_controller.rb new file mode 100644 index 0000000..ae08768 --- /dev/null +++ b/app/controllers/comments_controller.rb @@ -0,0 +1,67 @@ +# frozen_string_literal: true + +class CommentsController < ApplicationController + before_action :set_comment, only: %i[show update destroy] + before_action :set_post, only: %i[index create] + + # GET /posts/:post_id/comments + def index + @comments = @post.comments + + render json: @comments + end + + # GET /comments/:id + def show + render json: @comment + end + + # POST /posts/:post_id/comments + def create + @comment = @post.comments.new(comment_params) + @comment.user_id = @current_user.id + + if @comment.save + render json: @comment, status: :created, location: @comment + else + render json: @comment.errors, status: :unprocessable_entity + end + end + + # PATCH/PUT /comments/:id + def update + check_user_permission_for(@comment) do |comment| + if comment.update(comment_params) + render json: comment, status: :ok + else + render json: comment.errors, status: :unprocessable_entity + end + end + end + + # DELETE /comments/:id + def destroy + check_user_permission_for(@comment) do |comment| + comment.destroy + head :no_content + end + end + + private + + # Use callbacks to share common setup or constraints between actions. + def set_comment + @comment = Comment.find_by_id(params[:id]) + raise CommentNotFoundException if @comment.blank? + end + + def set_post + @post = Post.find_by_id(params[:post_id]) + raise PostNotFoundException if @post.blank? + end + + # Only allow a list of trusted parameters through. + def comment_params + params.require(:comment).permit(:content) + end +end diff --git a/app/controllers/concerns/application_concern.rb b/app/controllers/concerns/application_concern.rb new file mode 100644 index 0000000..015ecbd --- /dev/null +++ b/app/controllers/concerns/application_concern.rb @@ -0,0 +1,33 @@ +# frozen_string_literal: true + +module ApplicationConcern + extend ActiveSupport::Concern + + included do + attr_reader :current_user + + before_action :authorize_api_request!, only: %i[create update destroy] + end + + private + + def authorize_api_request! + @current_user = ApiRequest.new(request.headers).authorize! + raise UnauthorizedException unless @current_user + end + + # resource can be either post, comment, reply + def check_user_permission_for(resource) + raise UnpermittedException if @current_user.id != resource.user_id + + raise LocalJumpError, 'block is not given to execute' unless block_given? + + yield(resource) + end +end + +class UnpermittedException < StandardError; end +class UnauthorizedException < StandardError; end +class CommentNotFoundException < StandardError; end +class PostNotFoundException < StandardError; end +class InvalidTokenException < StandardError; end diff --git a/app/controllers/concerns/exception_handler.rb b/app/controllers/concerns/exception_handler.rb new file mode 100644 index 0000000..3f7cf74 --- /dev/null +++ b/app/controllers/concerns/exception_handler.rb @@ -0,0 +1,56 @@ +# frozen_string_literal: true + +module ExceptionHandler + extend ActiveSupport::Concern + + included do + rescue_from UnpermittedException, with: :unpermitted_exception_handler + rescue_from UnauthorizedException, with: :unauthorized_exception + rescue_from ActiveRecord::RecordInvalid, with: :record_invalid + rescue_from ActiveRecord::RecordNotFound, with: :record_not_found + rescue_from CommentNotFoundException, with: :comment_not_found + rescue_from PostNotFoundException, with: :post_not_found + rescue_from InvalidTokenException, with: :invalid_token_exception_handler + end + + private + + # Handlers + def unpermitted_exception_handler + render_error_response 'Forbidden', :forbidden + end + + def invalid_token_exception_handler + msg = 'Invalid authorization token' + render_error_response msg, :unauthorized + end + + def post_not_found + msg = %(Post not found) + render_error_response msg, :not_found + end + + def comment_not_found + msg = %(Comment not found) + render_error_response msg, :not_found + end + + def record_invalid + render_error_response 'Invalid data', :unprocessable_entity + end + + # responses + + def record_not_found + render_error_response 'Not found', :not_found + end + + def unauthorized_exception + render_error_response 'Unauthorized Request', :unauthorized + end + + ## + def render_error_response(msg, status) + render json: { okay: false, error: msg }, status: status + end +end diff --git a/app/controllers/posts_controller.rb b/app/controllers/posts_controller.rb new file mode 100644 index 0000000..00d7257 --- /dev/null +++ b/app/controllers/posts_controller.rb @@ -0,0 +1,60 @@ +# frozen_string_literal: true + +class PostsController < ApplicationController + before_action :set_post, only: %i[show update destroy] + + # GET /posts + def index + @posts = Post.includes(:comments).page(params[:p]) + + render json: @posts + end + + # GET /posts/1 + def show + render json: @post + end + + # POST /posts + def create + @post = @current_user.posts.new(post_params) + + if @post.save + render json: @post, status: :created, location: @post + else + render json: @post.errors, status: :unprocessable_entity + end + end + + # PATCH/PUT /posts/1 + def update + check_user_permission_for(@post) do |post| + if post.update(post_params) + render json: post, status: :ok + else + render json: post.errors, status: :unprocessable_entity + end + end + end + + # DELETE /posts/1 + def destroy + check_user_permission_for(@post) do |post| + post.destroy + head :no_content + end + end + + private + + # Use callbacks to share common setup or constraints between actions. + def set_post + @post = Post.find_by_id(params[:id]) + raise PostNotFoundException if @post.blank? + end + + # Only allow a list of trusted parameters through. + def post_params + params.require(:post).permit(:title, :content) + end +end diff --git a/app/controllers/registration_controller.rb b/app/controllers/registration_controller.rb new file mode 100644 index 0000000..41d85ad --- /dev/null +++ b/app/controllers/registration_controller.rb @@ -0,0 +1,36 @@ +# frozen_string_literal: true + +class RegistrationController < ApplicationController + skip_before_action :authorize_api_request!, only: %i[create] + + # POST /register + def create + user = User.new register_params + if user.save + render json: { okay: true, authorization: user.token_get }, status: :created + else + render_error_response user.errors, :unprocessable_entity + end + end + + # DELETE /users + def destroy + pwd = delete_params[:confirmation_password] + if @current_user.authenticate(pwd) + @current_user.destroy + head :no_content + else + render json: { okay: false, reason: 'Incorrect email or password' }, status: :unauthorized + end + end + + private + + def register_params + params.require(:user).permit(:first_name, :last_name, :email, :password, :password_confirmation) + end + + def delete_params + params.permit(:confirmation_password) + end +end diff --git a/app/jobs/application_job.rb b/app/jobs/application_job.rb new file mode 100644 index 0000000..bef3959 --- /dev/null +++ b/app/jobs/application_job.rb @@ -0,0 +1,9 @@ +# frozen_string_literal: true + +class ApplicationJob < ActiveJob::Base + # Automatically retry jobs that encountered a deadlock + # retry_on ActiveRecord::Deadlocked + + # Most jobs are safe to ignore if the underlying records are no longer available + # discard_on ActiveJob::DeserializationError +end diff --git a/app/mailers/application_mailer.rb b/app/mailers/application_mailer.rb new file mode 100644 index 0000000..d84cb6e --- /dev/null +++ b/app/mailers/application_mailer.rb @@ -0,0 +1,6 @@ +# frozen_string_literal: true + +class ApplicationMailer < ActionMailer::Base + default from: 'from@example.com' + layout 'mailer' +end diff --git a/app/models/application_record.rb b/app/models/application_record.rb new file mode 100644 index 0000000..08dc537 --- /dev/null +++ b/app/models/application_record.rb @@ -0,0 +1,5 @@ +# frozen_string_literal: true + +class ApplicationRecord < ActiveRecord::Base + primary_abstract_class +end diff --git a/app/models/comment.rb b/app/models/comment.rb new file mode 100644 index 0000000..e1895dd --- /dev/null +++ b/app/models/comment.rb @@ -0,0 +1,8 @@ +# frozen_string_literal: true + +class Comment < ApplicationRecord + belongs_to :user + belongs_to :post + + self.per_page = 10 +end diff --git a/app/models/concerns/user_concern.rb b/app/models/concerns/user_concern.rb new file mode 100644 index 0000000..5c7e42e --- /dev/null +++ b/app/models/concerns/user_concern.rb @@ -0,0 +1,27 @@ +# frozen_string_literal: true + +module UserConcern + extend ActiveSupport::Concern + + included do + validates :email, :first_name, presence: true + validates :email, uniqueness: true + validates :first_name, length: { within: 1..30 } + validates :password, length: { minimum: 6 } + validates_format_of :email, with: /[a-z0-9]+@/i + + has_secure_password + end + + def authenticate(pwd) + password == pwd + end + + def token_get + JsonWebToken.encode({ email: email }) + end + + def full_name + "#{first_name} #{last_name}" + end +end diff --git a/app/models/post.rb b/app/models/post.rb new file mode 100644 index 0000000..5f5fba5 --- /dev/null +++ b/app/models/post.rb @@ -0,0 +1,8 @@ +# frozen_string_literal: true + +class Post < ApplicationRecord + belongs_to :user + has_many :comments, dependent: :destroy + + self.per_page = 10 +end diff --git a/app/models/user.rb b/app/models/user.rb new file mode 100644 index 0000000..d620d51 --- /dev/null +++ b/app/models/user.rb @@ -0,0 +1,8 @@ +# frozen_string_literal: true + +class User < ApplicationRecord + has_many :posts, dependent: :destroy + has_many :comments, dependent: :destroy + + include UserConcern +end diff --git a/app/serializers/comment_serializer.rb b/app/serializers/comment_serializer.rb new file mode 100644 index 0000000..7213064 --- /dev/null +++ b/app/serializers/comment_serializer.rb @@ -0,0 +1,5 @@ +class CommentSerializer < ActiveModel::Serializer + attributes :id, :content, :created_at + + belongs_to :user +end diff --git a/app/serializers/post_serializer.rb b/app/serializers/post_serializer.rb new file mode 100644 index 0000000..97b087b --- /dev/null +++ b/app/serializers/post_serializer.rb @@ -0,0 +1,12 @@ +class PostSerializer < ActiveModel::Serializer + attributes :id, :title, :content, :created_at, :comments + + belongs_to :user + # has_many :comments + + def comments + { + count: object.comments.count + } + end +end diff --git a/app/serializers/user_serializer.rb b/app/serializers/user_serializer.rb new file mode 100644 index 0000000..8a7f950 --- /dev/null +++ b/app/serializers/user_serializer.rb @@ -0,0 +1,3 @@ +class UserSerializer < ActiveModel::Serializer + attributes :id, :full_name +end diff --git a/app/services/api_request.rb b/app/services/api_request.rb new file mode 100644 index 0000000..caa9d84 --- /dev/null +++ b/app/services/api_request.rb @@ -0,0 +1,25 @@ +# frozen_string_literal: true + +class ApiRequest + attr_reader :headers + + def initialize(request_headers) + @request_headers = request_headers + end + + def authorize! + raise InvalidTokenException if user_data_get.blank? + + User.find_by_email(user_data_get['email']) + end + + private + + def user_data_get + JsonWebToken.decode(authorization_token) + end + + def authorization_token + @request_headers['Authorization'].split(/\s+/).last if @request_headers['Authorization'].present? + end +end diff --git a/app/services/authenticate_user.rb b/app/services/authenticate_user.rb new file mode 100644 index 0000000..dbcb7c7 --- /dev/null +++ b/app/services/authenticate_user.rb @@ -0,0 +1,20 @@ +# frozen_string_literal: true + +class AuthenticateUser + attr_reader :params + + def initialize(params) + @params = params + end + + def call + user + end + + def user + user = User.find_by_email(@params['email']) + return user.token_get if user&.authenticate(@params['password']) + end + + private :user +end diff --git a/app/views/layouts/mailer.html.erb b/app/views/layouts/mailer.html.erb new file mode 100644 index 0000000..cbd34d2 --- /dev/null +++ b/app/views/layouts/mailer.html.erb @@ -0,0 +1,13 @@ + + + + + + + + + <%= yield %> + + diff --git a/app/views/layouts/mailer.text.erb b/app/views/layouts/mailer.text.erb new file mode 100644 index 0000000..37f0bdd --- /dev/null +++ b/app/views/layouts/mailer.text.erb @@ -0,0 +1 @@ +<%= yield %> diff --git a/bin/bundle b/bin/bundle new file mode 100755 index 0000000..19d9450 --- /dev/null +++ b/bin/bundle @@ -0,0 +1,114 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# +# This file was generated by Bundler. +# +# The application 'bundle' is installed as part of a gem, and +# this file is here to facilitate running it. +# + +require 'rubygems' + +m = Module.new do + module_function + + def invoked_as_script? + File.expand_path($0) == File.expand_path(__FILE__) + end + + def env_var_version + ENV['BUNDLER_VERSION'] + end + + def cli_arg_version + return unless invoked_as_script? # don't want to hijack other binstubs + return unless 'update'.start_with?(ARGV.first || ' ') # must be running `bundle update` + bundler_version = nil + update_index = nil + ARGV.each_with_index do |a, i| + if update_index && update_index.succ == i && a =~ Gem::Version::ANCHORED_VERSION_PATTERN + bundler_version = a + end + next unless a =~ /\A--bundler(?:[= ](#{Gem::Version::VERSION_PATTERN}))?\z/ + bundler_version = $1 + update_index = i + end + bundler_version + end + + def gemfile + gemfile = ENV['BUNDLE_GEMFILE'] + return gemfile if gemfile && !gemfile.empty? + + File.expand_path('../../Gemfile', __FILE__) + end + + def lockfile + lockfile = + case File.basename(gemfile) + when 'gems.rb' then gemfile.sub(/\.rb$/, gemfile) + else "#{gemfile}.lock" + end + File.expand_path(lockfile) + end + + def lockfile_version + return unless File.file?(lockfile) + lockfile_contents = File.read(lockfile) + return unless lockfile_contents =~ /\n\nBUNDLED WITH\n\s{2,}(#{Gem::Version::VERSION_PATTERN})\n/ + Regexp.last_match(1) + end + + def bundler_requirement + @bundler_requirement ||= + env_var_version || cli_arg_version || + bundler_requirement_for(lockfile_version) + end + + def bundler_requirement_for(version) + return "#{Gem::Requirement.default}.a" unless version + + bundler_gem_version = Gem::Version.new(version) + + requirement = bundler_gem_version.approximate_recommendation + + return requirement unless Gem::Version.new(Gem::VERSION) < Gem::Version.new("2.7.0") + + requirement += ".a" if bundler_gem_version.prerelease? + + requirement + end + + def load_bundler! + ENV['BUNDLE_GEMFILE'] ||= gemfile + + activate_bundler + end + + def activate_bundler + gem_error = activation_error_handling do + gem "bundler", bundler_requirement + end + return if gem_error.nil? + require_error = activation_error_handling do + require "bundler/version" + end + return if require_error.nil? && Gem::Requirement.new(bundler_requirement).satisfied_by?(Gem::Version.new(Bundler::VERSION)) + warn "Activating bundler (#{bundler_requirement}) failed:\n#{gem_error.message}\n\nTo install the version of bundler this project requires, run `gem install bundler -v '#{bundler_requirement}'`" + exit 42 + end + + def activation_error_handling + yield + nil + rescue StandardError, LoadError => e + e + end +end + +m.load_bundler! + +if m.invoked_as_script? + load Gem.bin_path('bundler', 'bundle') +end diff --git a/bin/rails b/bin/rails new file mode 100755 index 0000000..0739660 --- /dev/null +++ b/bin/rails @@ -0,0 +1,4 @@ +#!/usr/bin/env ruby +APP_PATH = File.expand_path('../config/application', __dir__) +require_relative '../config/boot' +require 'rails/commands' diff --git a/bin/rake b/bin/rake new file mode 100755 index 0000000..1724048 --- /dev/null +++ b/bin/rake @@ -0,0 +1,4 @@ +#!/usr/bin/env ruby +require_relative '../config/boot' +require 'rake' +Rake.application.run diff --git a/bin/setup b/bin/setup new file mode 100755 index 0000000..d6e019a --- /dev/null +++ b/bin/setup @@ -0,0 +1,33 @@ +#!/usr/bin/env ruby +require 'fileutils' + +# path to your application root. +APP_ROOT = File.expand_path('..', __dir__) + +def system!(*args) + system(*args) || abort("\n== Command #{args} failed ==") +end + +FileUtils.chdir APP_ROOT do + # This script is a way to set up or update your development environment automatically. + # This script is idempotent, so that you can run it at any time and get an expectable outcome. + # Add necessary setup steps to this file. + + puts '== Installing dependencies ==' + system! 'gem install bundler --conservative' + system('bundle check') || system!('bundle install') + + # puts "\n== Copying sample files ==" + # unless File.exist?("config/database.yml") + # FileUtils.cp "config/database.yml.sample", "config/database.yml" + # end + + puts "\n== Preparing database ==" + system! 'bin/rails db:prepare' + + puts "\n== Removing old logs and tempfiles ==" + system! 'bin/rails log:clear tmp:clear' + + puts "\n== Restarting application server ==" + system! 'bin/rails restart' +end diff --git a/config.ru b/config.ru new file mode 100644 index 0000000..ad1fbf2 --- /dev/null +++ b/config.ru @@ -0,0 +1,6 @@ +# This file is used by Rack-based servers to start the application. + +require_relative 'config/environment' + +run Rails.application +Rails.application.load_server diff --git a/config/application.rb b/config/application.rb new file mode 100644 index 0000000..b86fddd --- /dev/null +++ b/config/application.rb @@ -0,0 +1,30 @@ +require_relative 'boot' + +require 'rails/all' + +# Require the gems listed in Gemfile, including any gems +# you've limited to :test, :development, or :production. +Bundler.require(*Rails.groups) + +module BlogApiApp + class Application < Rails::Application + # Initialize configuration defaults for originally generated Rails version. + config.load_defaults 7.0 + + config.autoload_paths << Rails.root.join('lib') + config.autoload_paths << Rails.root.join('app','services') + + # Configuration for the application, engines, and railties goes here. + # + # These settings can be overridden in specific environments using the files + # in config/environments, which are processed later. + # + # config.time_zone = "Central Time (US & Canada)" + # config.eager_load_paths << Rails.root.join("extras") + + # Only loads a smaller set of middleware suitable for API only apps. + # Middleware like session, flash, cookies can be added back manually. + # Skip views, helpers and assets when generating a new resource. + config.api_only = true + end +end diff --git a/config/boot.rb b/config/boot.rb new file mode 100644 index 0000000..b9e460c --- /dev/null +++ b/config/boot.rb @@ -0,0 +1,4 @@ +ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__) + +require 'bundler/setup' # Set up gems listed in the Gemfile. +require 'bootsnap/setup' # Speed up boot time by caching expensive operations. diff --git a/config/cable.yml b/config/cable.yml new file mode 100644 index 0000000..a7ead2e --- /dev/null +++ b/config/cable.yml @@ -0,0 +1,10 @@ +development: + adapter: async + +test: + adapter: test + +production: + adapter: redis + url: <%= ENV.fetch("REDIS_URL") { "redis://localhost:6379/1" } %> + channel_prefix: blog_api_app_production diff --git a/config/credentials.yml.enc b/config/credentials.yml.enc new file mode 100644 index 0000000..10ee7fa --- /dev/null +++ b/config/credentials.yml.enc @@ -0,0 +1 @@ +3+q6VT+CEbNwHAqIwmzQW/tWJVXu9/zhEHMHlNt804u2YI+4buLZhGbda6sWhkCmeVi/cOtImxCxS/pq7hOy1nqG6ds0/80C2jVlPnDSHsvbkJptmm//jdaKg1zDS4rDhnMlwYICPN1AP78edV2RIJB22RDmSIWcY5ZBFIYbQf0RJ2isYFbRVdWnaw6CB03xTOVPJX1WnefHkDr0OtAyZILqNMioYPjYdMKy/k09sJJI87aH4Z7IG7Xuaivxezo09CgDa/jJOkG9kFBTfulB1TjyTcnaSNL9ZTm9pCq3bflI2/G+pdgDY7iVWw6bEY0jqNBH+RJ/je+My1Q6Ga5JgssbfA4IuQChvpe/guElCgM9bjsMdMVkCdSBYouxDpl4kLQ6CcODGFepMTkkr+zYIdrZpBspWbyDQX5D--ntA12s66N80zvXFP--FghlT+w8TpohyF/9d/lvQQ== \ No newline at end of file diff --git a/config/database.yml b/config/database.yml new file mode 100644 index 0000000..2700deb --- /dev/null +++ b/config/database.yml @@ -0,0 +1,21 @@ +common: &common + pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> + timeout: 5000 + +development: + <<: *common + adapter: sqlite3 + database: db/development.sqlite3 + +# Warning: The database defined as "test" will be erased and +# re-generated from your development database when you run "rake". +# Do not set this db to the same as development or production. +test: + <<: *common + adapter: sqlite3 + database: db/test.sqlite3 + +production: + adapter: postgres + <<: *common + database: db/production.sqlite3 diff --git a/config/environment.rb b/config/environment.rb new file mode 100644 index 0000000..426333b --- /dev/null +++ b/config/environment.rb @@ -0,0 +1,5 @@ +# Load the Rails application. +require_relative 'application' + +# Initialize the Rails application. +Rails.application.initialize! diff --git a/config/environments/development.rb b/config/environments/development.rb new file mode 100644 index 0000000..680e793 --- /dev/null +++ b/config/environments/development.rb @@ -0,0 +1,65 @@ +require 'active_support/core_ext/integer/time' + +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # In the development environment your application's code is reloaded any time + # it changes. This slows down response time but is perfect for development + # since you don't have to restart the web server when you make code changes. + config.cache_classes = false + + # Do not eager load code on boot. + config.eager_load = false + + # Show full error reports. + config.consider_all_requests_local = true + + # Enable server timing + config.server_timing = true + + # Enable/disable caching. By default caching is disabled. + # Run rails dev:cache to toggle caching. + if Rails.root.join('tmp/caching-dev.txt').exist? + config.cache_store = :memory_store + config.public_file_server.headers = { + 'Cache-Control' => "public, max-age=#{2.days.to_i}" + } + else + config.action_controller.perform_caching = false + + config.cache_store = :null_store + end + + # Store uploaded files on the local file system (see config/storage.yml for options). + config.active_storage.service = :local + + # Don't care if the mailer can't send. + config.action_mailer.raise_delivery_errors = false + + config.action_mailer.perform_caching = false + + # Print deprecation notices to the Rails logger. + config.active_support.deprecation = :log + + # Raise exceptions for disallowed deprecations. + config.active_support.disallowed_deprecation = :raise + + # Tell Active Support which deprecation messages to disallow. + config.active_support.disallowed_deprecation_warnings = [] + + # Raise an error on page load if there are pending migrations. + config.active_record.migration_error = :page_load + + # Highlight code that triggered database queries in logs. + config.active_record.verbose_query_logs = true + + + # Raises error for missing translations. + # config.i18n.raise_on_missing_translations = true + + # Annotate rendered view with file names. + # config.action_view.annotate_rendered_view_with_filenames = true + + # Uncomment if you wish to allow Action Cable access from any origin. + # config.action_cable.disable_request_forgery_protection = true +end diff --git a/config/environments/production.rb b/config/environments/production.rb new file mode 100644 index 0000000..fb33d3f --- /dev/null +++ b/config/environments/production.rb @@ -0,0 +1,86 @@ +require 'active_support/core_ext/integer/time' + +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # Code is not reloaded between requests. + config.cache_classes = true + + # Eager load code on boot. This eager loads most of Rails and + # your application in memory, allowing both threaded web servers + # and those relying on copy on write to perform better. + # Rake tasks automatically ignore this option for performance. + config.eager_load = true + + # Full error reports are disabled and caching is turned on. + config.consider_all_requests_local = false + + # Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"] + # or in config/master.key. This key is used to decrypt credentials (and other encrypted files). + # config.require_master_key = true + + # Disable serving static files from the `/public` folder by default since + # Apache or NGINX already handles this. + config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? + + # Enable serving of images, stylesheets, and JavaScripts from an asset server. + # config.asset_host = "http://assets.example.com" + + # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for Apache + # Specifies the header that your server uses for sending files. + # config.action_dispatch.x_sendfile_header = "X-Accel-Redirect" # for NGINX + + # Store uploaded files on the local file system (see config/storage.yml for options). + config.active_storage.service = :local + + # Mount Action Cable outside main process or domain. + # config.action_cable.mount_path = nil + # config.action_cable.url = "wss://example.com/cable" + # config.action_cable.allowed_request_origins = [ "http://example.com", /http:\/\/example.*/ ] + + # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. + # config.force_ssl = true + + # Include generic and useful information about system operation, but avoid logging too much + # information to avoid inadvertent exposure of personally identifiable information (PII). + config.log_level = :info + + # Prepend all log lines with the following tags. + config.log_tags = [ :request_id ] + + # Use a different cache store in production. + # config.cache_store = :mem_cache_store + + # Use a real queuing backend for Active Job (and separate queues per environment). + # config.active_job.queue_adapter = :resque + # config.active_job.queue_name_prefix = "blog_api_app_production" + + config.action_mailer.perform_caching = false + + # Ignore bad email addresses and do not raise email delivery errors. + # Set this to true and configure the email server for immediate delivery to raise delivery errors. + # config.action_mailer.raise_delivery_errors = false + + # Enable locale fallbacks for I18n (makes lookups for any locale fall back to + # the I18n.default_locale when a translation cannot be found). + config.i18n.fallbacks = true + + # Don't log any deprecations. + config.active_support.report_deprecations = false + + # Use default logging formatter so that PID and timestamp are not suppressed. + config.log_formatter = ::Logger::Formatter.new + + # Use a different logger for distributed setups. + # require "syslog/logger" + # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new "app-name") + + if ENV['RAILS_LOG_TO_STDOUT'].present? + logger = ActiveSupport::Logger.new(STDOUT) + logger.formatter = config.log_formatter + config.logger = ActiveSupport::TaggedLogging.new(logger) + end + + # Do not dump schema after migrations. + config.active_record.dump_schema_after_migration = false +end diff --git a/config/environments/test.rb b/config/environments/test.rb new file mode 100644 index 0000000..618aebd --- /dev/null +++ b/config/environments/test.rb @@ -0,0 +1,60 @@ +require "active_support/core_ext/integer/time" + +# The test environment is used exclusively to run your application's +# test suite. You never need to work with it otherwise. Remember that +# your test database is "scratch space" for the test suite and is wiped +# and recreated between test runs. Don't rely on the data there! + +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # Turn false under Spring and add config.action_view.cache_template_loading = true + config.cache_classes = true + + # Eager loading loads your whole application. When running a single test locally, + # this probably isn't necessary. It's a good idea to do in a continuous integration + # system, or in some way before deploying your code. + config.eager_load = ENV["CI"].present? + + # Configure public file server for tests with Cache-Control for performance. + config.public_file_server.enabled = true + config.public_file_server.headers = { + "Cache-Control" => "public, max-age=#{1.hour.to_i}" + } + + # Show full error reports and disable caching. + config.consider_all_requests_local = true + config.action_controller.perform_caching = false + config.cache_store = :null_store + + # Raise exceptions instead of rendering exception templates. + config.action_dispatch.show_exceptions = false + + # Disable request forgery protection in test environment. + config.action_controller.allow_forgery_protection = false + + # Store uploaded files on the local file system in a temporary directory. + config.active_storage.service = :test + + config.action_mailer.perform_caching = false + + # Tell Action Mailer not to deliver emails to the real world. + # The :test delivery method accumulates sent emails in the + # ActionMailer::Base.deliveries array. + config.action_mailer.delivery_method = :test + + # Print deprecation notices to the stderr. + config.active_support.deprecation = :stderr + + # Raise exceptions for disallowed deprecations. + config.active_support.disallowed_deprecation = :raise + + # Tell Active Support which deprecation messages to disallow. + config.active_support.disallowed_deprecation_warnings = [] + + # Raises error for missing translations. + # config.i18n.raise_on_missing_translations = true + + # Annotate rendered view with file names. + # config.action_view.annotate_rendered_view_with_filenames = true +end diff --git a/config/initializers/cors.rb b/config/initializers/cors.rb new file mode 100644 index 0000000..e51307e --- /dev/null +++ b/config/initializers/cors.rb @@ -0,0 +1,16 @@ +# Be sure to restart your server when you modify this file. + +# Avoid CORS issues when API is called from the frontend app. +# Handle Cross-Origin Resource Sharing (CORS) in order to accept cross-origin AJAX requests. + +# Read more: https://github.com/cyu/rack-cors + +Rails.application.config.middleware.insert_before 0, Rack::Cors do + allow do + origins '*' + + resource "*", + headers: :any, + methods: [:get, :post, :put, :patch, :delete, :options, :head] + end +end diff --git a/config/initializers/filter_parameter_logging.rb b/config/initializers/filter_parameter_logging.rb new file mode 100644 index 0000000..3e69694 --- /dev/null +++ b/config/initializers/filter_parameter_logging.rb @@ -0,0 +1,6 @@ +# Be sure to restart your server when you modify this file. + +# Configure sensitive parameters which will be filtered from the log file. +Rails.application.config.filter_parameters += %i[ + passw secret token _key crypt salt certificate otp ssn +] diff --git a/config/initializers/inflections.rb b/config/initializers/inflections.rb new file mode 100644 index 0000000..3860f65 --- /dev/null +++ b/config/initializers/inflections.rb @@ -0,0 +1,16 @@ +# Be sure to restart your server when you modify this file. + +# Add new inflection rules using the following format. Inflections +# are locale specific, and you may define rules for as many different +# locales as you wish. All of these examples are active by default: +# ActiveSupport::Inflector.inflections(:en) do |inflect| +# inflect.plural /^(ox)$/i, "\\1en" +# inflect.singular /^(ox)en/i, "\\1" +# inflect.irregular "person", "people" +# inflect.uncountable %w( fish sheep ) +# end + +# These inflection rules are supported but not enabled by default: +# ActiveSupport::Inflector.inflections(:en) do |inflect| +# inflect.acronym "RESTful" +# end diff --git a/config/locales/en.yml b/config/locales/en.yml new file mode 100644 index 0000000..8ca56fc --- /dev/null +++ b/config/locales/en.yml @@ -0,0 +1,33 @@ +# Files in the config/locales directory are used for internationalization +# and are automatically loaded by Rails. If you want to use locales other +# than English, add the necessary files in this directory. +# +# To use the locales, use `I18n.t`: +# +# I18n.t "hello" +# +# In views, this is aliased to just `t`: +# +# <%= t("hello") %> +# +# To use a different locale, set it with `I18n.locale`: +# +# I18n.locale = :es +# +# This would use the information in config/locales/es.yml. +# +# The following keys must be escaped otherwise they will not be retrieved by +# the default I18n backend: +# +# true, false, on, off, yes, no +# +# Instead, surround them with single quotes. +# +# en: +# "true": "foo" +# +# To learn more, please read the Rails Internationalization guide +# available at https://guides.rubyonrails.org/i18n.html. + +en: + hello: "Hello world" diff --git a/config/puma.rb b/config/puma.rb new file mode 100644 index 0000000..e9dc159 --- /dev/null +++ b/config/puma.rb @@ -0,0 +1,43 @@ +# Puma can serve each request in a thread from an internal thread pool. +# The `threads` method setting takes two numbers: a minimum and maximum. +# Any libraries that use thread pools should be configured to match +# the maximum value specified for Puma. Default is set to 5 threads for minimum +# and maximum; this matches the default thread size of Active Record. +# +max_threads_count = ENV.fetch('RAILS_MAX_THREADS') { 5 } +min_threads_count = ENV.fetch('RAILS_MIN_THREADS') { max_threads_count } +threads min_threads_count, max_threads_count + +# Specifies the `worker_timeout` threshold that Puma will use to wait before +# terminating a worker in development environments. +# +worker_timeout 3600 if ENV.fetch('RAILS_ENV', 'development') == 'development' + +# Specifies the `port` that Puma will listen on to receive requests; default is 3000. +# +port ENV.fetch('PORT') { 3000 } + +# Specifies the `environment` that Puma will run in. +# +environment ENV.fetch('RAILS_ENV') { 'development' } + +# Specifies the `pidfile` that Puma will use. +pidfile ENV.fetch('PIDFILE') { 'tmp/pids/server.pid' } + +# Specifies the number of `workers` to boot in clustered mode. +# Workers are forked web server processes. If using threads and workers together +# the concurrency of the application would be max `threads` * `workers`. +# Workers do not work on JRuby or Windows (both of which do not support +# processes). +# +# workers ENV.fetch("WEB_CONCURRENCY") { 2 } + +# Use the `preload_app!` method when specifying a `workers` number. +# This directive tells Puma to first boot the application and load code +# before forking the application. This takes advantage of Copy On Write +# process behavior so workers use less memory. +# +# preload_app! + +# Allow puma to be restarted by `bin/rails restart` command. +plugin :tmp_restart diff --git a/config/routes.rb b/config/routes.rb new file mode 100644 index 0000000..e2808ae --- /dev/null +++ b/config/routes.rb @@ -0,0 +1,11 @@ +Rails.application.routes.draw do + root 'authentication#create' + + post 'register' => 'registration#create' + post 'login' => 'authentication#create' + delete 'users' => 'registration#destroy' + + resources :posts do + resources :comments, shallow: true + end +end diff --git a/config/storage.yml b/config/storage.yml new file mode 100644 index 0000000..4942ab6 --- /dev/null +++ b/config/storage.yml @@ -0,0 +1,34 @@ +test: + service: Disk + root: <%= Rails.root.join("tmp/storage") %> + +local: + service: Disk + root: <%= Rails.root.join("storage") %> + +# Use bin/rails credentials:edit to set the AWS secrets (as aws:access_key_id|secret_access_key) +# amazon: +# service: S3 +# access_key_id: <%= Rails.application.credentials.dig(:aws, :access_key_id) %> +# secret_access_key: <%= Rails.application.credentials.dig(:aws, :secret_access_key) %> +# region: us-east-1 +# bucket: your_own_bucket-<%= Rails.env %> + +# Remember not to checkin your GCS keyfile to a repository +# google: +# service: GCS +# project: your_project +# credentials: <%= Rails.root.join("path/to/gcs.keyfile") %> +# bucket: your_own_bucket-<%= Rails.env %> + +# Use bin/rails credentials:edit to set the Azure Storage secret (as azure_storage:storage_access_key) +# microsoft: +# service: AzureStorage +# storage_account_name: your_account_name +# storage_access_key: <%= Rails.application.credentials.dig(:azure_storage, :storage_access_key) %> +# container: your_container_name-<%= Rails.env %> + +# mirror: +# service: Mirror +# primary: local +# mirrors: [ amazon, google, microsoft ] diff --git a/db/migrate/20211229075018_create_users.rb b/db/migrate/20211229075018_create_users.rb new file mode 100644 index 0000000..7dbf721 --- /dev/null +++ b/db/migrate/20211229075018_create_users.rb @@ -0,0 +1,12 @@ +class CreateUsers < ActiveRecord::Migration[7.0] + def change + create_table :users do |t| + t.string :first_name, limit: 30, null: false + t.string :last_name, limit: 30 + t.string :email, null: false + t.string :password_digest, null: false + + t.timestamps + end + end +end diff --git a/db/migrate/20211229075051_create_posts.rb b/db/migrate/20211229075051_create_posts.rb new file mode 100644 index 0000000..9855648 --- /dev/null +++ b/db/migrate/20211229075051_create_posts.rb @@ -0,0 +1,11 @@ +class CreatePosts < ActiveRecord::Migration[7.0] + def change + create_table :posts do |t| + t.string :title + t.text :content, null: false + t.belongs_to :user, null: false, foreign_key: true + + t.timestamps + end + end +end diff --git a/db/migrate/20220102104002_create_comments.rb b/db/migrate/20220102104002_create_comments.rb new file mode 100644 index 0000000..fee8109 --- /dev/null +++ b/db/migrate/20220102104002_create_comments.rb @@ -0,0 +1,11 @@ +class CreateComments < ActiveRecord::Migration[7.0] + def change + create_table :comments do |t| + t.belongs_to :user, null: false, foreign_key: true + t.belongs_to :post, null: false, foreign_key: true + t.text :content + + t.timestamps + end + end +end diff --git a/db/schema.rb b/db/schema.rb new file mode 100644 index 0000000..21d0279 --- /dev/null +++ b/db/schema.rb @@ -0,0 +1,46 @@ +# This file is auto-generated from the current state of the database. Instead +# of editing this file, please use the migrations feature of Active Record to +# incrementally modify your database, and then regenerate this schema definition. +# +# This file is the source Rails uses to define your schema when running `bin/rails +# db:schema:load`. When creating a new database, `bin/rails db:schema:load` tends to +# be faster and is potentially less error prone than running all of your +# migrations from scratch. Old migrations may fail to apply correctly if those +# migrations use external dependencies or application code. +# +# It's strongly recommended that you check this file into your version control system. + +ActiveRecord::Schema.define(version: 2022_01_02_104002) do + + create_table "comments", force: :cascade do |t| + t.integer "user_id", null: false + t.integer "post_id", null: false + t.text "content" + t.datetime "created_at", precision: 6, null: false + t.datetime "updated_at", precision: 6, null: false + t.index ["post_id"], name: "index_comments_on_post_id" + t.index ["user_id"], name: "index_comments_on_user_id" + end + + create_table "posts", force: :cascade do |t| + t.string "title" + t.text "content", null: false + t.integer "user_id", null: false + t.datetime "created_at", precision: 6, null: false + t.datetime "updated_at", precision: 6, null: false + t.index ["user_id"], name: "index_posts_on_user_id" + end + + create_table "users", force: :cascade do |t| + t.string "first_name", limit: 30, null: false + t.string "last_name", limit: 30 + t.string "email", null: false + t.string "password_digest", null: false + t.datetime "created_at", precision: 6, null: false + t.datetime "updated_at", precision: 6, null: false + end + + add_foreign_key "comments", "posts" + add_foreign_key "comments", "users" + add_foreign_key "posts", "users" +end diff --git a/db/seeds.rb b/db/seeds.rb new file mode 100644 index 0000000..b9d26ef --- /dev/null +++ b/db/seeds.rb @@ -0,0 +1,33 @@ +puts 'creating account ....' + +# User +10.times do + pwd = Faker::Internet.password + hash = { first_name: Faker::Name.unique.name, email: Faker::Internet.email } + hash.merge!({ password: pwd }) + user = User.new(hash) + user.password_confirmation = pwd + user.save +end + +# POSTS +@user = User.first +puts 'creating posts ....' +50.times do + title = Faker::Lorem.sentence + content = Faker::Lorem.sentence(word_count: 30) + hash = { title: title, content: content } + @user.posts.new(hash).save +end + +# comments +puts 'creating comment ....' + +post = Post.first +100.times do + content = Faker::Lorem.sentence(word_count: 30) + hash = { content: content } + koment = post.comments.new(hash) + koment.user = User.second + koment.save +end diff --git a/idea.txt b/idea.txt new file mode 100644 index 0000000..890afc4 --- /dev/null +++ b/idea.txt @@ -0,0 +1,15 @@ +# IDEA + +1: add to support comment replies + +2: add to support attachments(images) + +## Optional + +3: add follower feature + => followers + => followings + +4: make to support read/unread feature + +5: show unread posts in root route(home page) from followings people diff --git a/lib/json_web_token.rb b/lib/json_web_token.rb new file mode 100644 index 0000000..295e946 --- /dev/null +++ b/lib/json_web_token.rb @@ -0,0 +1,26 @@ +# frozen_string_literal: true + +module CustomeImplementation + def encode(payload, exp = 6.hours.from_now) + payload[:exp] = exp.to_i + JWT.encode payload, hmac_secret, 'HS256' + end + + def decode(token) + JWT.decode(token, hmac_secret, { algorithm: 'HS256' }).first + rescue JWT::DecodeError + nil + end + + def hmac_secret + Rails.application.secrets.secret_key_base + end + + private :hmac_secret +end + +class JsonWebToken + class << self + include CustomeImplementation + end +end diff --git a/lib/tasks/.keep b/lib/tasks/.keep new file mode 100644 index 0000000..e69de29 diff --git a/log/.keep b/log/.keep new file mode 100644 index 0000000..e69de29 diff --git a/public/robots.txt b/public/robots.txt new file mode 100644 index 0000000..c19f78a --- /dev/null +++ b/public/robots.txt @@ -0,0 +1 @@ +# See https://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file diff --git a/storage/.keep b/storage/.keep new file mode 100644 index 0000000..e69de29 diff --git a/test/channels/application_cable/connection_test.rb b/test/channels/application_cable/connection_test.rb new file mode 100644 index 0000000..800405f --- /dev/null +++ b/test/channels/application_cable/connection_test.rb @@ -0,0 +1,11 @@ +require "test_helper" + +class ApplicationCable::ConnectionTest < ActionCable::Connection::TestCase + # test "connects with cookies" do + # cookies.signed[:user_id] = 42 + # + # connect + # + # assert_equal connection.user_id, "42" + # end +end diff --git a/test/controllers/authentication_controller_test.rb b/test/controllers/authentication_controller_test.rb new file mode 100644 index 0000000..666aa9d --- /dev/null +++ b/test/controllers/authentication_controller_test.rb @@ -0,0 +1,22 @@ +require 'test_helper' + +class AuthenticationControllerTest < ActionDispatch::IntegrationTest + setup do + @user = users(:leecrey) + @data = { email: @user.email, password: 'incorrect password' } + end + + test 'should be unauthorized' do + post login_url, params: { user: @data }, as: :json + assert_response :unauthorized + + assert_equal @response.body, %({"okay":false,"error":"Invalid data"}) + end + + test 'should be authorized' do + # correct password + @data[:password] = 'hello world' + post login_url, params: { user: @data }, as: :json + assert_response :success + end +end diff --git a/test/controllers/comments_controller_test.rb b/test/controllers/comments_controller_test.rb new file mode 100644 index 0000000..f87735f --- /dev/null +++ b/test/controllers/comments_controller_test.rb @@ -0,0 +1,72 @@ +require 'test_helper' + +class CommentsControllerTest < ActionDispatch::IntegrationTest + setup do + @user = users(:leecrey) + @post = posts(:first) + @comment = comments(:first) + @token = @user.token_get + end + + test 'should get index' do + get post_comments_path(@post), as: :json + assert_response :success + end + + test 'should not create comment' do + @token += 'x' + assert_difference('Comment.count', 0) do + post post_comments_path(@post), + headers: { Authorization: @token }, + params: { comment: { content: @comment.content, post_id: @comment.post_id, user_id: @comment.user_id } }, + as: :json + end + + assert_response :unauthorized + end + + test 'should create comment' do + assert_difference('Comment.count') do + post post_comments_path(@post), + headers: { Authorization: @token }, + params: { comment: { content: @comment.content, post_id: @comment.post_id, user_id: @comment.user_id } }, + as: :json + end + + assert_response :created + end + + test 'should not show comment' do + url = 'http://localhost:3000/comments/32' + get url, as: :json + assert_response :not_found + end + + test 'should show comment' do + get comment_url(@comment), as: :json + assert_response :success + end + + test 'should update comment' do + content = 'New content' + hash = { content: content, post_id: @comment.post_id, user_id: @comment.user_id } + patch comment_url(@comment), headers: { Authorization: @token }, params: { comment: hash }, as: :json + assert_response :success + end + + test 'should not destroy comment' do + assert_difference('Comment.count', 0) do + delete comment_url(@comment), headers: { Authorization: @token + 'x' }, as: :json + end + + assert_response :unauthorized + end + + test 'should destroy comment' do + assert_difference('Comment.count', -1) do + delete comment_url(@comment), headers: { Authorization: @token }, as: :json + end + + assert_response :no_content + end +end diff --git a/test/controllers/posts_controller_test.rb b/test/controllers/posts_controller_test.rb new file mode 100644 index 0000000..2e05d6a --- /dev/null +++ b/test/controllers/posts_controller_test.rb @@ -0,0 +1,73 @@ +require 'test_helper' + +class PostsControllerTest < ActionDispatch::IntegrationTest + setup do + @david = users(:david) + @user = users(:leecrey) + @post = posts(:first) + end + + test 'should get index' do + get posts_url, as: :json + assert_response :success + end + + test 'should be un authorized' do + token = @user.token_get + 'xyz' + hash = { content: @post.content, user_id: @post.user_id } + post posts_url, headers: { Authorization: token }, + params: { post: hash }, + as: :json + + assert_response :unauthorized + end + + test 'should create post' do + token = @user.token_get + assert_difference('Post.count') do + post posts_url, headers: { Authorization: token }, + params: { post: { content: @post.content, user_id: @post.user_id } }, + as: :json + end + + assert_response :created + end + + test 'should show post' do + get post_url(@post), as: :json + assert_response :success + end + + test 'should be unauthorized' do + hash = { content: @post.content, user_id: @post.user_id } + patch post_url(@post), params: { post: hash }, as: :json + assert_response :unauthorized + end + + test 'should update post' do + token = @user.token_get + hash = { content: @post.content, user_id: @post.user_id } + patch post_url(@post), headers: { Authorization: token }, + params: { post: hash }, as: :json + assert_response :success + end + + test 'should not be destroyed' do + # david is trying to delete leecrey's post + token = @david.token_get + assert_difference('Post.count', 0) do + delete post_url(@post), headers: { Authorization: token }, as: :json + end + + assert_response :forbidden + end + + test 'should destroy post' do + token = @user.token_get + assert_difference('Post.count', -1) do + delete post_url(@post), headers: { Authorization: token }, as: :json + end + + assert_response :no_content + end +end diff --git a/test/controllers/registration_controller_test.rb b/test/controllers/registration_controller_test.rb new file mode 100644 index 0000000..cb810be --- /dev/null +++ b/test/controllers/registration_controller_test.rb @@ -0,0 +1,37 @@ +require 'test_helper' + +class RegistrationControllerTest < ActionDispatch::IntegrationTest + setup do + @user = users(:leecrey) + # email is already exist + @data = { first_name: @user.first_name, email: @user.email, password: 'hello world' } + @data.merge!({ password_confirmation: 'hello world' }) + end + + test 'should return error' do + post register_url, params: { user: @data }, as: :json + assert_response :unprocessable_entity + assert_equal @response.body, %({"okay":false,"error":{"email":["has already been taken"]}}) + end + + test 'should return authorization token' do + # email changed here + @data[:email] = 'changed-email@gmail.com' + post register_url, params: { user: @data }, as: :json + assert_response :created, 'Expecting authorization token but did not get' + end + + test 'should return authorization error' do + # random garbage token + token = JsonWebToken.encode({ email: 'leecrey@gmail.com' }) + delete users_url, headers: { 'Authorization': token }, as: :json + assert_response :unauthorized, 'request was authorized with wrong token' + end + + test 'should remove account' do + token = @user.token_get + delete users_url, headers: { 'Authorization': token }, + params: { confirmation_password: 'hello world' }, as: :json + assert_response :no_content, 'request was unauthorized with correct token' + end +end diff --git a/test/fixtures/comments.yml b/test/fixtures/comments.yml new file mode 100644 index 0000000..48da844 --- /dev/null +++ b/test/fixtures/comments.yml @@ -0,0 +1,4 @@ +first: + user: leecrey + post: first + content: this is sample comment diff --git a/test/fixtures/posts.yml b/test/fixtures/posts.yml new file mode 100644 index 0000000..8c4e125 --- /dev/null +++ b/test/fixtures/posts.yml @@ -0,0 +1,10 @@ +first: + user: leecrey + title: hello world + content: this is test content + + +second: + user: david + title: my very first post + content: Valid with wrong confirmation password diff --git a/test/fixtures/users.yml b/test/fixtures/users.yml new file mode 100644 index 0000000..8e5aa9e --- /dev/null +++ b/test/fixtures/users.yml @@ -0,0 +1,13 @@ +# Read about fixtures at https://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html + +leecrey: + first_name: Lee + email: already-taken@gmail.com + # password: hello world + password_digest: $2a$12$8tD0mfwPrbRrEtWPzYKIiOteVE6FouqSLWcPrxZOEe3GJQQaUMUPy + +david: + first_name: David + email: david11@gmail.com + # password: hello-world + password_digest: $2a$12$cqqLsDIg3wsQS68rNDueheBVB.sk.WU9I43nCXORpKyxJganyBNh. diff --git a/test/integration/.keep b/test/integration/.keep new file mode 100644 index 0000000..e69de29 diff --git a/test/mailers/.keep b/test/mailers/.keep new file mode 100644 index 0000000..e69de29 diff --git a/test/models/comment_test.rb b/test/models/comment_test.rb new file mode 100644 index 0000000..4166db6 --- /dev/null +++ b/test/models/comment_test.rb @@ -0,0 +1,11 @@ +require 'test_helper' + +class CommentTest < ActiveSupport::TestCase + setup do + @lee_crey = users(:leecrey) + end + + # test "the truth" do + # assert true + # end +end diff --git a/test/models/post_test.rb b/test/models/post_test.rb new file mode 100644 index 0000000..b63afd1 --- /dev/null +++ b/test/models/post_test.rb @@ -0,0 +1,25 @@ +require 'test_helper' + +class PostTest < ActiveSupport::TestCase + setup do + @lee_crey = users(:leecrey) + end + + test 'should not create post without body and user id' do + assert_not Post.new.save, 'Post created without body and user id' + end + + test 'should raise non null constrain exception without content' do + assert_raises(ActiveRecord::NotNullViolation) do + Post.new(user_id: @lee_crey.id).save + end + end + + test 'should not create post without user id' do + assert_not Post.new(content: 'hello world').save, 'created post without user id' + end + + test 'should create post' do + assert Post.new(content: 'hello world', user_id: @lee_crey.id).save, 'not able to create post' + end +end diff --git a/test/models/user_test.rb b/test/models/user_test.rb new file mode 100644 index 0000000..4306f59 --- /dev/null +++ b/test/models/user_test.rb @@ -0,0 +1,47 @@ +require 'test_helper' + +class UserTest < ActiveSupport::TestCase + setup do + @user = User.new({ first_name: 'Solomon', email: 'already-taken@gmail.com' }) + @user.password = 'hello world' + @user.password_confirmation = 'hello world' + end + + test 'should not be valid with' do + # with existing email + assert_not @user.valid?, 'Valid with already taken email' + + # with wrong confirmation password + @user.password_confirmation = 'hello world32' + assert_not @user.valid?, 'Valid with wrong confirmation password' + + # with wrong password length + @user.password = 'hello' + @user.password_confirmation = 'hello' + assert_not @user.valid?, 'User is valid with invalid password length' + + # with empty first_name + @user.first_name = '' + @user.password = 'hello world' + @user.password_confirmation = 'hello world' + assert_not @user.valid?, 'Valid with empty first name but it should not' + + # with first_name length 31 + @user.first_name = %(Lorem ipsum dolor sit amet cons) + assert_not @user.valid?, "Valid with invalid first name length #{@user.first_name.size}" + + # with invalid email + @user.first_name = 'Solomon' + @user.email = 'wrong-email' + assert_not @user.valid?, "User is valid with invalid email address #{@user.email}" + end + + test 'should be valid' do + @user.email = 'correct-email@gmail.com' + @user.first_name = %(Lorem ipsum dolor sit amet co) + assert @user.valid?, 'Invalid with valid first name' + + # save + assert @user.save, 'Can not create with valid data' + end +end diff --git a/test/test_helper.rb b/test/test_helper.rb new file mode 100644 index 0000000..d5300f8 --- /dev/null +++ b/test/test_helper.rb @@ -0,0 +1,13 @@ +ENV['RAILS_ENV'] ||= 'test' +require_relative '../config/environment' +require 'rails/test_help' + +class ActiveSupport::TestCase + # Run tests in parallel with specified workers + parallelize(workers: :number_of_processors) + + # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order. + fixtures :all + + # Add more helper methods to be used by all tests here... +end diff --git a/tmp/.keep b/tmp/.keep new file mode 100644 index 0000000..e69de29 diff --git a/vendor/.keep b/vendor/.keep new file mode 100644 index 0000000..e69de29