diff --git a/week_4/activity-tracker/Gemfile b/week_4/activity-tracker/Gemfile index 413b15ae..f6469688 100644 --- a/week_4/activity-tracker/Gemfile +++ b/week_4/activity-tracker/Gemfile @@ -41,6 +41,7 @@ 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 "devise" # Use Sass to process CSS # gem "sassc-rails" diff --git a/week_4/activity-tracker/Gemfile.lock b/week_4/activity-tracker/Gemfile.lock index e8909a06..c6e4f082 100644 --- a/week_4/activity-tracker/Gemfile.lock +++ b/week_4/activity-tracker/Gemfile.lock @@ -68,6 +68,7 @@ GEM tzinfo (~> 2.0) addressable (2.8.1) public_suffix (>= 2.0.2, < 6.0) + bcrypt (3.1.18) bindex (0.8.1) bootsnap (1.15.0) msgpack (~> 1.2) @@ -87,6 +88,12 @@ GEM debug (1.7.1) irb (>= 1.5.0) reline (>= 0.3.1) + devise (4.8.1) + bcrypt (~> 3.0) + orm_adapter (~> 0.1) + railties (>= 4.1.0) + responders + warden (~> 1.2.3) erubi (1.12.0) globalid (1.0.0) activesupport (>= 5.0) @@ -127,6 +134,7 @@ GEM nio4r (2.5.8) nokogiri (1.14.0-x86_64-linux) racc (~> 1.4) + orm_adapter (0.5.0) public_suffix (5.0.1) puma (5.6.5) nio4r (~> 2.0) @@ -168,6 +176,9 @@ GEM regexp_parser (2.6.1) reline (0.3.2) io-console (~> 0.5) + responders (3.1.0) + actionpack (>= 5.2) + railties (>= 5.2) rexml (3.2.5) rubyzip (2.3.2) selenium-webdriver (4.7.1) @@ -192,6 +203,8 @@ GEM railties (>= 6.0.0) tzinfo (2.0.5) concurrent-ruby (~> 1.0) + warden (1.2.9) + rack (>= 2.0.9) web-console (4.2.0) actionview (>= 6.0.0) activemodel (>= 6.0.0) @@ -216,6 +229,7 @@ DEPENDENCIES bootsnap capybara debug + devise importmap-rails jbuilder puma (~> 5.0) diff --git a/week_4/activity-tracker/app/controllers/activities_controller.rb b/week_4/activity-tracker/app/controllers/activities_controller.rb new file mode 100644 index 00000000..a1dc90c1 --- /dev/null +++ b/week_4/activity-tracker/app/controllers/activities_controller.rb @@ -0,0 +1,70 @@ +class ActivitiesController < ApplicationController + before_action :set_activity, only: %i[ show edit update destroy ] + + # GET /activities or /activities.json + def index + @activities = Activity.all + end + + # GET /activities/1 or /activities/1.json + def show + end + + # GET /activities/new + def new + @activity = Activity.new + end + + # GET /activities/1/edit + def edit + end + + # POST /activities or /activities.json + def create + @activity = Activity.new(activity_params) + + respond_to do |format| + if @activity.save + format.html { redirect_to activity_url(@activity), notice: "Activity was successfully created." } + format.json { render :show, status: :created, location: @activity } + else + format.html { render :new, status: :unprocessable_entity } + format.json { render json: @activity.errors, status: :unprocessable_entity } + end + end + end + + # PATCH/PUT /activities/1 or /activities/1.json + def update + respond_to do |format| + if @activity.update(activity_params) + format.html { redirect_to activity_url(@activity), notice: "Activity was successfully updated." } + format.json { render :show, status: :ok, location: @activity } + else + format.html { render :edit, status: :unprocessable_entity } + format.json { render json: @activity.errors, status: :unprocessable_entity } + end + end + end + + # DELETE /activities/1 or /activities/1.json + def destroy + @activity.destroy + + respond_to do |format| + format.html { redirect_to activities_url, notice: "Activity was successfully destroyed." } + format.json { head :no_content } + end + end + + private + # Use callbacks to share common setup or constraints between actions. + def set_activity + @activity = Activity.find(params[:id]) + end + + # Only allow a list of trusted parameters through. + def activity_params + params.require(:activity).permit(:title, :activity_type, :start, :duration, :calories) + end +end diff --git a/week_4/activity-tracker/app/controllers/application_controller.rb b/week_4/activity-tracker/app/controllers/application_controller.rb index 09705d12..6b4dcfa8 100644 --- a/week_4/activity-tracker/app/controllers/application_controller.rb +++ b/week_4/activity-tracker/app/controllers/application_controller.rb @@ -1,2 +1,3 @@ class ApplicationController < ActionController::Base + before_action :authenticate_user! end diff --git a/week_4/activity-tracker/app/controllers/home_controller.rb b/week_4/activity-tracker/app/controllers/home_controller.rb new file mode 100644 index 00000000..a2381f3f --- /dev/null +++ b/week_4/activity-tracker/app/controllers/home_controller.rb @@ -0,0 +1,6 @@ +class HomeController < ApplicationController + skip_before_action :authenticate_user!, only: %i[index] + def index + end + +end diff --git a/week_4/activity-tracker/app/controllers/stats_controller.rb b/week_4/activity-tracker/app/controllers/stats_controller.rb new file mode 100644 index 00000000..5ea249bd --- /dev/null +++ b/week_4/activity-tracker/app/controllers/stats_controller.rb @@ -0,0 +1,14 @@ +class StatsController < ApplicationController + + def index + @total_duration = 0 + @total_calorie = 0 + activities = Activity.all; + activities.each do |activity| + @total_duration += activity.duration + @total_calorie += activity.calories + end + end + +end + diff --git a/week_4/activity-tracker/app/helpers/activities_helper.rb b/week_4/activity-tracker/app/helpers/activities_helper.rb new file mode 100644 index 00000000..4e9784cc --- /dev/null +++ b/week_4/activity-tracker/app/helpers/activities_helper.rb @@ -0,0 +1,2 @@ +module ActivitiesHelper +end diff --git a/week_4/activity-tracker/app/helpers/home_helper.rb b/week_4/activity-tracker/app/helpers/home_helper.rb new file mode 100644 index 00000000..23de56ac --- /dev/null +++ b/week_4/activity-tracker/app/helpers/home_helper.rb @@ -0,0 +1,2 @@ +module HomeHelper +end diff --git a/week_4/activity-tracker/app/helpers/stats_helper.rb b/week_4/activity-tracker/app/helpers/stats_helper.rb new file mode 100644 index 00000000..65e2f8bb --- /dev/null +++ b/week_4/activity-tracker/app/helpers/stats_helper.rb @@ -0,0 +1,2 @@ +module StatsHelper +end diff --git a/week_4/activity-tracker/app/models/activity.rb b/week_4/activity-tracker/app/models/activity.rb new file mode 100644 index 00000000..a99f990d --- /dev/null +++ b/week_4/activity-tracker/app/models/activity.rb @@ -0,0 +1,2 @@ +class Activity < ApplicationRecord +end diff --git a/week_4/activity-tracker/app/models/user.rb b/week_4/activity-tracker/app/models/user.rb new file mode 100644 index 00000000..47567994 --- /dev/null +++ b/week_4/activity-tracker/app/models/user.rb @@ -0,0 +1,6 @@ +class User < ApplicationRecord + # Include default devise modules. Others available are: + # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable + devise :database_authenticatable, :registerable, + :recoverable, :rememberable, :validatable +end diff --git a/week_4/activity-tracker/app/views/activities/_activity.html.erb b/week_4/activity-tracker/app/views/activities/_activity.html.erb new file mode 100644 index 00000000..aab462e3 --- /dev/null +++ b/week_4/activity-tracker/app/views/activities/_activity.html.erb @@ -0,0 +1,27 @@ +
+

+ Title: + <%= activity.title %> +

+ +

+ Activity type: + <%= activity.activity_type %> +

+ +

+ Start: + <%= activity.start %> +

+ +

+ Duration: + <%= activity.duration %> +

+ +

+ Calories: + <%= activity.calories %> +

+ +
diff --git a/week_4/activity-tracker/app/views/activities/_activity.json.jbuilder b/week_4/activity-tracker/app/views/activities/_activity.json.jbuilder new file mode 100644 index 00000000..8efbd331 --- /dev/null +++ b/week_4/activity-tracker/app/views/activities/_activity.json.jbuilder @@ -0,0 +1,2 @@ +json.extract! activity, :id, :title, :activity_type, :start, :duration, :calories, :created_at, :updated_at +json.url activity_url(activity, format: :json) diff --git a/week_4/activity-tracker/app/views/activities/_form.html.erb b/week_4/activity-tracker/app/views/activities/_form.html.erb new file mode 100644 index 00000000..6d4079c4 --- /dev/null +++ b/week_4/activity-tracker/app/views/activities/_form.html.erb @@ -0,0 +1,42 @@ +<%= form_with(model: activity) do |form| %> + <% if activity.errors.any? %> +
+

<%= pluralize(activity.errors.count, "error") %> prohibited this activity from being saved:

+ + +
+ <% end %> + +
+ <%= form.label :title, style: "display: block" %> + <%= form.text_field :title %> +
+ +
+ <%= form.label :activity_type, style: "display: block" %> + <%= form.text_field :activity_type %> +
+ +
+ <%= form.label :start, style: "display: block" %> + <%= form.datetime_field :start %> +
+ +
+ <%= form.label :duration, style: "display: block" %> + <%= form.text_field :duration %> +
+ +
+ <%= form.label :calories, style: "display: block" %> + <%= form.number_field :calories %> +
+ +
+ <%= form.submit %> +
+<% end %> diff --git a/week_4/activity-tracker/app/views/activities/edit.html.erb b/week_4/activity-tracker/app/views/activities/edit.html.erb new file mode 100644 index 00000000..4774a05e --- /dev/null +++ b/week_4/activity-tracker/app/views/activities/edit.html.erb @@ -0,0 +1,10 @@ +

Editing activity

+ +<%= render "form", activity: @activity %> + +
+ +
+ <%= link_to "Show this activity", @activity %> | + <%= link_to "Back to activities", activities_path %> +
diff --git a/week_4/activity-tracker/app/views/activities/index.html.erb b/week_4/activity-tracker/app/views/activities/index.html.erb new file mode 100644 index 00000000..776f9042 --- /dev/null +++ b/week_4/activity-tracker/app/views/activities/index.html.erb @@ -0,0 +1,14 @@ +

<%= notice %>

+ +

Activities

+ +
+ <% @activities.each do |activity| %> + <%= render activity %> +

+ <%= link_to "Show this activity", activity %> +

+ <% end %> +
+ +<%= link_to "New activity", new_activity_path %> diff --git a/week_4/activity-tracker/app/views/activities/index.json.jbuilder b/week_4/activity-tracker/app/views/activities/index.json.jbuilder new file mode 100644 index 00000000..865f89ee --- /dev/null +++ b/week_4/activity-tracker/app/views/activities/index.json.jbuilder @@ -0,0 +1 @@ +json.array! @activities, partial: "activities/activity", as: :activity diff --git a/week_4/activity-tracker/app/views/activities/new.html.erb b/week_4/activity-tracker/app/views/activities/new.html.erb new file mode 100644 index 00000000..855a5899 --- /dev/null +++ b/week_4/activity-tracker/app/views/activities/new.html.erb @@ -0,0 +1,9 @@ +

New activity

+ +<%= render "form", activity: @activity %> + +
+ +
+ <%= link_to "Back to activities", activities_path %> +
diff --git a/week_4/activity-tracker/app/views/activities/show.html.erb b/week_4/activity-tracker/app/views/activities/show.html.erb new file mode 100644 index 00000000..73be1e19 --- /dev/null +++ b/week_4/activity-tracker/app/views/activities/show.html.erb @@ -0,0 +1,10 @@ +

<%= notice %>

+ +<%= render @activity %> + +
+ <%= link_to "Edit this activity", edit_activity_path(@activity) %> | + <%= link_to "Back to activities", activities_path %> + + <%= button_to "Destroy this activity", @activity, method: :delete %> +
diff --git a/week_4/activity-tracker/app/views/activities/show.json.jbuilder b/week_4/activity-tracker/app/views/activities/show.json.jbuilder new file mode 100644 index 00000000..a145d0a8 --- /dev/null +++ b/week_4/activity-tracker/app/views/activities/show.json.jbuilder @@ -0,0 +1 @@ +json.partial! "activities/activity", activity: @activity diff --git a/week_4/activity-tracker/app/views/home/index.html.erb b/week_4/activity-tracker/app/views/home/index.html.erb new file mode 100644 index 00000000..b0bfbd87 --- /dev/null +++ b/week_4/activity-tracker/app/views/home/index.html.erb @@ -0,0 +1,11 @@ +

Welcome To Activity Tracker

+<% if user_signed_in? %> +
Logged in as : <%= current_user.email %>

+ <%= link_to "Activities", activities_path %>

+ <%= link_to "Stats", "/activities/stats" %>

+ <%= button_to "Log out", destroy_user_session_path, method: :delete %> +<% else %> +

Sign In To See Activities

+ <%= link_to "Sign In", new_user_session_path %>

+ <%= link_to "Sign Up", new_user_registration_path %> +<%end %> \ No newline at end of file diff --git a/week_4/activity-tracker/app/views/layouts/application.html.erb b/week_4/activity-tracker/app/views/layouts/application.html.erb index 5f65d83d..69abb352 100644 --- a/week_4/activity-tracker/app/views/layouts/application.html.erb +++ b/week_4/activity-tracker/app/views/layouts/application.html.erb @@ -11,6 +11,8 @@ - <%= yield %> +

<%= notice %>

+

<%= alert %>

+ <%= yield %> diff --git a/week_4/activity-tracker/app/views/stats/index.html.erb b/week_4/activity-tracker/app/views/stats/index.html.erb new file mode 100644 index 00000000..ffd563d3 --- /dev/null +++ b/week_4/activity-tracker/app/views/stats/index.html.erb @@ -0,0 +1,3 @@ +

Activities Stats

+

Total Duration : <%= @total_duration %>

+

Total Calories : <%= @total_calorie %>

\ No newline at end of file diff --git a/week_4/activity-tracker/config/initializers/devise.rb b/week_4/activity-tracker/config/initializers/devise.rb new file mode 100644 index 00000000..80fcfee5 --- /dev/null +++ b/week_4/activity-tracker/config/initializers/devise.rb @@ -0,0 +1,312 @@ +# 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 = 'e8c1b284eb9f0cd032671f2b90bb6a9ddfffc13fe47adba8fc36f6cc8a698da615d26018457b8def6d889ee10f5b35657cd63f333982421826d9c4f0306431eb' + + # ==> 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' + config.navigational_formats = ['*/*', :html, :turbo_stream] + + # 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 = '1602a35552904edd9929db1a0670e0ca6540418d144cf59d34dee4466a1958d5ad29e7efd3210919d9a363bd14aeeccc72d3443bbed795f2aa92d95dfccf2c6a' + + # 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 +end diff --git a/week_4/activity-tracker/config/locales/devise.en.yml b/week_4/activity-tracker/config/locales/devise.en.yml new file mode 100644 index 00000000..260e1c4b --- /dev/null +++ b/week_4/activity-tracker/config/locales/devise.en.yml @@ -0,0 +1,65 @@ +# 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." + 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:" diff --git a/week_4/activity-tracker/config/routes.rb b/week_4/activity-tracker/config/routes.rb index 7ff20da4..9d585e44 100644 --- a/week_4/activity-tracker/config/routes.rb +++ b/week_4/activity-tracker/config/routes.rb @@ -1,5 +1,11 @@ Rails.application.routes.draw do - + devise_for :users + resources :activities do + collection do + get 'stats', to: 'stats#index' + end + end + root 'home#index' # Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html # Defines the root path route ("/") diff --git a/week_4/activity-tracker/db/migrate/20230205173223_create_activities.rb b/week_4/activity-tracker/db/migrate/20230205173223_create_activities.rb new file mode 100644 index 00000000..d0fe3b06 --- /dev/null +++ b/week_4/activity-tracker/db/migrate/20230205173223_create_activities.rb @@ -0,0 +1,13 @@ +class CreateActivities < ActiveRecord::Migration[7.0] + def change + create_table :activities do |t| + t.string :title + t.string :activity_type + t.datetime :start + t.decimal :duration + t.integer :calories + + t.timestamps + end + end +end diff --git a/week_4/activity-tracker/db/migrate/20230205213322_devise_create_users.rb b/week_4/activity-tracker/db/migrate/20230205213322_devise_create_users.rb new file mode 100644 index 00000000..43927dbd --- /dev/null +++ b/week_4/activity-tracker/db/migrate/20230205213322_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/week_4/activity-tracker/db/schema.rb b/week_4/activity-tracker/db/schema.rb index a3b04951..92ea8486 100644 --- a/week_4/activity-tracker/db/schema.rb +++ b/week_4/activity-tracker/db/schema.rb @@ -10,5 +10,27 @@ # # 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: 2023_02_05_213322) do + create_table "activities", force: :cascade do |t| + t.string "title" + t.string "activity_type" + t.datetime "start" + t.decimal "duration" + t.integer "calories" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + 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.index ["email"], name: "index_users_on_email", unique: true + t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true + end + end diff --git a/week_4/activity-tracker/test/controllers/activities_controller_test.rb b/week_4/activity-tracker/test/controllers/activities_controller_test.rb index f1d89c50..dec4d257 100644 --- a/week_4/activity-tracker/test/controllers/activities_controller_test.rb +++ b/week_4/activity-tracker/test/controllers/activities_controller_test.rb @@ -45,15 +45,4 @@ class ActivitiesControllerTest < ActionDispatch::IntegrationTest assert_redirected_to activities_url end - - test "should get stats" do - get stats_activities_url - assert_response :success - expected_calories = Activity.sum(&:calories) - expected_duration = Activity.sum(&:duration) - cal = assigns(:total_calories) - dur = assigns(:total_duration) - assert_equal(expected_calories, cal) - assert_equal(expected_duration, dur) - end end diff --git a/week_4/activity-tracker/test/controllers/home_controller_test.rb b/week_4/activity-tracker/test/controllers/home_controller_test.rb new file mode 100644 index 00000000..eac0e336 --- /dev/null +++ b/week_4/activity-tracker/test/controllers/home_controller_test.rb @@ -0,0 +1,7 @@ +require "test_helper" + +class HomeControllerTest < ActionDispatch::IntegrationTest + # test "the truth" do + # assert true + # end +end diff --git a/week_4/activity-tracker/test/controllers/stats_controller_test.rb b/week_4/activity-tracker/test/controllers/stats_controller_test.rb new file mode 100644 index 00000000..65d8eb91 --- /dev/null +++ b/week_4/activity-tracker/test/controllers/stats_controller_test.rb @@ -0,0 +1,7 @@ +require "test_helper" + +class StatsControllerTest < ActionDispatch::IntegrationTest + # test "the truth" do + # assert true + # end +end diff --git a/week_4/activity-tracker/test/fixtures/activities.yml b/week_4/activity-tracker/test/fixtures/activities.yml new file mode 100644 index 00000000..f1684d0a --- /dev/null +++ b/week_4/activity-tracker/test/fixtures/activities.yml @@ -0,0 +1,15 @@ +# Read about fixtures at https://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html + +one: + title: MyString + activity_type: MyString + start: 2023-02-05 23:02:23 + duration: 9.99 + calories: 1 + +two: + title: MyString + activity_type: MyString + start: 2023-02-05 23:02:23 + duration: 9.99 + calories: 1 diff --git a/week_4/activity-tracker/test/fixtures/users.yml b/week_4/activity-tracker/test/fixtures/users.yml new file mode 100644 index 00000000..d7a33292 --- /dev/null +++ b/week_4/activity-tracker/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/week_4/activity-tracker/test/models/activity_test.rb b/week_4/activity-tracker/test/models/activity_test.rb new file mode 100644 index 00000000..c07a8b91 --- /dev/null +++ b/week_4/activity-tracker/test/models/activity_test.rb @@ -0,0 +1,7 @@ +require "test_helper" + +class ActivityTest < ActiveSupport::TestCase + # test "the truth" do + # assert true + # end +end diff --git a/week_4/activity-tracker/test/models/user_test.rb b/week_4/activity-tracker/test/models/user_test.rb new file mode 100644 index 00000000..5c07f490 --- /dev/null +++ b/week_4/activity-tracker/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/week_4/activity-tracker/test/system/activities_test.rb b/week_4/activity-tracker/test/system/activities_test.rb new file mode 100644 index 00000000..15feb5a2 --- /dev/null +++ b/week_4/activity-tracker/test/system/activities_test.rb @@ -0,0 +1,49 @@ +require "application_system_test_case" + +class ActivitiesTest < ApplicationSystemTestCase + setup do + @activity = activities(:one) + end + + test "visiting the index" do + visit activities_url + assert_selector "h1", text: "Activities" + end + + test "should create activity" do + visit activities_url + click_on "New activity" + + fill_in "Activity type", with: @activity.activity_type + fill_in "Calories", with: @activity.calories + fill_in "Duration", with: @activity.duration + fill_in "Start", with: @activity.start + fill_in "Title", with: @activity.title + click_on "Create Activity" + + assert_text "Activity was successfully created" + click_on "Back" + end + + test "should update Activity" do + visit activity_url(@activity) + click_on "Edit this activity", match: :first + + fill_in "Activity type", with: @activity.activity_type + fill_in "Calories", with: @activity.calories + fill_in "Duration", with: @activity.duration + fill_in "Start", with: @activity.start + fill_in "Title", with: @activity.title + click_on "Update Activity" + + assert_text "Activity was successfully updated" + click_on "Back" + end + + test "should destroy Activity" do + visit activity_url(@activity) + click_on "Destroy this activity", match: :first + + assert_text "Activity was successfully destroyed" + end +end diff --git a/week_5/README.md b/week_5/README.md new file mode 100644 index 00000000..c322665f --- /dev/null +++ b/week_5/README.md @@ -0,0 +1,17 @@ +# Week 4 + +Hello! Hope you are having a wonderful time at the bootcamp. For this week, we will look into controllers, routing and authentication. You can find the links to the documents below. + +- [Controllers](./activity-tracker/README.md) +- [Authentication](./activity-tracker/authentication.md) + +## Assignement 1 +After going through the resource on controllers, it is time to make your own! Create a contoller action called `stats` that is invoked from the URL `/activities/stats/`. This controller action should define at least two *instance variables*: + +- `total_duration`: The total duration of all activity logged. +- `total_calories`: The total amount of calories burnt. + +Please ensure that you are able to access the URL from a browser. Also make sure that the variables are named **exactly** that. + +## Assignment 2 +Now that you have a functioning app ready, you need to protect it. You can't have anyone in the world access your activity logs, right? The task is simple - setup authentication! diff --git a/week_5/activity-tracker/.ruby-version b/week_5/activity-tracker/.ruby-version new file mode 100644 index 00000000..316881c9 --- /dev/null +++ b/week_5/activity-tracker/.ruby-version @@ -0,0 +1 @@ +ruby-3.0.5 diff --git a/week_5/activity-tracker/.tool-versions b/week_5/activity-tracker/.tool-versions new file mode 100644 index 00000000..4f7cf395 --- /dev/null +++ b/week_5/activity-tracker/.tool-versions @@ -0,0 +1,2 @@ +nodejs lts +ruby 3.0.5 diff --git a/week_5/activity-tracker/Gemfile b/week_5/activity-tracker/Gemfile new file mode 100644 index 00000000..bbdbe10b --- /dev/null +++ b/week_5/activity-tracker/Gemfile @@ -0,0 +1,76 @@ +source "https://rubygems.org" +git_source(:github) { |repo| "https://github.com/#{repo}.git" } + +ruby "3.0.5" + +# Bundle edge Rails instead: gem "rails", github: "rails/rails", branch: "main" +gem "rails", "~> 7.0.4" + +# The original asset pipeline for Rails [https://github.com/rails/sprockets-rails] +gem "sprockets-rails" + +# Use sqlite3 as the database for Active Record +gem "sqlite3", "~> 1.4" + +# Use the Puma web server [https://github.com/puma/puma] +gem "puma", "~> 5.0" + +# Use JavaScript with ESM import maps [https://github.com/rails/importmap-rails] +gem "importmap-rails" + +# Hotwire's SPA-like page accelerator [https://turbo.hotwired.dev] +gem "turbo-rails" + +# Hotwire's modest JavaScript framework [https://stimulus.hotwired.dev] +gem "stimulus-rails" + +# Build JSON APIs with ease [https://github.com/rails/jbuilder] +gem "jbuilder" + +# Use Redis adapter to run Action Cable in production +# gem "redis", "~> 4.0" + +# Use Kredis to get higher-level data types in Redis [https://github.com/rails/kredis] +# gem "kredis" + +# Use Active Model has_secure_password [https://guides.rubyonrails.org/active_model_basics.html#securepassword] +# 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 ] + +# Reduces boot times through caching; required in config/boot.rb +gem "bootsnap", require: false +gem "devise" + +# Use Sass to process CSS +# gem "sassc-rails" + +# Use Active Storage variants [https://guides.rubyonrails.org/active_storage_overview.html#transforming-images] +# gem "image_processing", "~> 1.2" + +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 ] +end + +group :development do + # Use console on exceptions pages [https://github.com/rails/web-console] + gem "web-console" + + # Add speed badges [https://github.com/MiniProfiler/rack-mini-profiler] + # gem "rack-mini-profiler" + + # Speed up commands on slow machines / big apps [https://github.com/rails/spring] + # gem "spring" +end + +group :test do + # Use system testing [https://guides.rubyonrails.org/testing.html#system-testing] + gem "capybara" + gem "selenium-webdriver" + gem "webdrivers" +end + +gem "rails-controller-testing" +gem 'bootstrap', '~> 5.2.2' \ No newline at end of file diff --git a/week_5/activity-tracker/Gemfile.lock b/week_5/activity-tracker/Gemfile.lock new file mode 100644 index 00000000..bc7790d9 --- /dev/null +++ b/week_5/activity-tracker/Gemfile.lock @@ -0,0 +1,270 @@ +GEM + remote: https://rubygems.org/ + specs: + actioncable (7.0.4) + actionpack (= 7.0.4) + activesupport (= 7.0.4) + nio4r (~> 2.0) + websocket-driver (>= 0.6.1) + actionmailbox (7.0.4) + actionpack (= 7.0.4) + activejob (= 7.0.4) + activerecord (= 7.0.4) + activestorage (= 7.0.4) + activesupport (= 7.0.4) + mail (>= 2.7.1) + net-imap + net-pop + net-smtp + actionmailer (7.0.4) + actionpack (= 7.0.4) + actionview (= 7.0.4) + activejob (= 7.0.4) + activesupport (= 7.0.4) + mail (~> 2.5, >= 2.5.4) + net-imap + net-pop + net-smtp + rails-dom-testing (~> 2.0) + actionpack (7.0.4) + actionview (= 7.0.4) + activesupport (= 7.0.4) + 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.4) + actionpack (= 7.0.4) + activerecord (= 7.0.4) + activestorage (= 7.0.4) + activesupport (= 7.0.4) + globalid (>= 0.6.0) + nokogiri (>= 1.8.5) + actionview (7.0.4) + activesupport (= 7.0.4) + builder (~> 3.1) + erubi (~> 1.4) + rails-dom-testing (~> 2.0) + rails-html-sanitizer (~> 1.1, >= 1.2.0) + activejob (7.0.4) + activesupport (= 7.0.4) + globalid (>= 0.3.6) + activemodel (7.0.4) + activesupport (= 7.0.4) + activerecord (7.0.4) + activemodel (= 7.0.4) + activesupport (= 7.0.4) + activestorage (7.0.4) + actionpack (= 7.0.4) + activejob (= 7.0.4) + activerecord (= 7.0.4) + activesupport (= 7.0.4) + marcel (~> 1.0) + mini_mime (>= 1.1.0) + activesupport (7.0.4) + concurrent-ruby (~> 1.0, >= 1.0.2) + i18n (>= 1.6, < 2) + minitest (>= 5.1) + tzinfo (~> 2.0) + addressable (2.8.1) + public_suffix (>= 2.0.2, < 6.0) + autoprefixer-rails (10.4.7.0) + execjs (~> 2) + bcrypt (3.1.18) + bindex (0.8.1) + bootsnap (1.15.0) + msgpack (~> 1.2) + bootstrap (5.2.3) + autoprefixer-rails (>= 9.1.0) + popper_js (>= 2.11.6, < 3) + sassc-rails (>= 2.0.0) + builder (3.2.4) + capybara (3.38.0) + addressable + matrix + mini_mime (>= 0.1.3) + nokogiri (~> 1.8) + rack (>= 1.6.0) + rack-test (>= 0.6.3) + regexp_parser (>= 1.5, < 3.0) + xpath (~> 3.2) + concurrent-ruby (1.1.10) + crass (1.0.6) + date (3.3.3) + debug (1.7.1) + irb (>= 1.5.0) + reline (>= 0.3.1) + devise (4.8.1) + bcrypt (~> 3.0) + orm_adapter (~> 0.1) + railties (>= 4.1.0) + responders + warden (~> 1.2.3) + erubi (1.12.0) + execjs (2.8.1) + ffi (1.15.5) + globalid (1.0.0) + activesupport (>= 5.0) + i18n (1.12.0) + concurrent-ruby (~> 1.0) + importmap-rails (1.1.5) + actionpack (>= 6.0.0) + railties (>= 6.0.0) + io-console (0.6.0) + irb (1.6.2) + reline (>= 0.3.0) + jbuilder (2.11.5) + actionview (>= 5.0.0) + activesupport (>= 5.0.0) + loofah (2.19.1) + crass (~> 1.0.2) + nokogiri (>= 1.5.9) + mail (2.8.0.1) + mini_mime (>= 0.1.1) + net-imap + net-pop + net-smtp + marcel (1.0.2) + matrix (0.4.2) + method_source (1.0.0) + mini_mime (1.1.2) + minitest (5.17.0) + msgpack (1.6.0) + net-imap (0.3.4) + date + net-protocol + net-pop (0.1.2) + net-protocol + net-protocol (0.2.1) + timeout + net-smtp (0.3.3) + net-protocol + nio4r (2.5.8) + nokogiri (1.14.0-x86_64-linux) + racc (~> 1.4) + orm_adapter (0.5.0) + popper_js (2.11.6) + public_suffix (5.0.1) + puma (5.6.5) + nio4r (~> 2.0) + racc (1.6.2) + rack (2.2.5) + rack-test (2.0.2) + rack (>= 1.3) + rails (7.0.4) + actioncable (= 7.0.4) + actionmailbox (= 7.0.4) + actionmailer (= 7.0.4) + actionpack (= 7.0.4) + actiontext (= 7.0.4) + actionview (= 7.0.4) + activejob (= 7.0.4) + activemodel (= 7.0.4) + activerecord (= 7.0.4) + activestorage (= 7.0.4) + activesupport (= 7.0.4) + bundler (>= 1.15.0) + railties (= 7.0.4) + 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) + rails-html-sanitizer (1.4.4) + loofah (~> 2.19, >= 2.19.1) + railties (7.0.4) + actionpack (= 7.0.4) + activesupport (= 7.0.4) + method_source + rake (>= 12.2) + thor (~> 1.0) + zeitwerk (~> 2.5) + rake (13.0.6) + regexp_parser (2.6.1) + reline (0.3.2) + io-console (~> 0.5) + responders (3.1.0) + actionpack (>= 5.2) + railties (>= 5.2) + rexml (3.2.5) + rubyzip (2.3.2) + sassc (2.4.0) + ffi (~> 1.9) + sassc-rails (2.1.2) + railties (>= 4.0.0) + sassc (>= 2.0) + sprockets (> 3.0) + sprockets-rails + tilt + selenium-webdriver (4.7.1) + rexml (~> 3.2, >= 3.2.5) + rubyzip (>= 1.2.2, < 3.0) + websocket (~> 1.0) + sprockets (4.2.0) + concurrent-ruby (~> 1.0) + rack (>= 2.2.4, < 4) + sprockets-rails (3.4.2) + actionpack (>= 5.2) + activesupport (>= 5.2) + sprockets (>= 3.0.0) + sqlite3 (1.5.4-x86_64-linux) + stimulus-rails (1.2.1) + railties (>= 6.0.0) + thor (1.2.1) + tilt (2.0.11) + timeout (0.3.1) + turbo-rails (1.3.2) + actionpack (>= 6.0.0) + activejob (>= 6.0.0) + railties (>= 6.0.0) + tzinfo (2.0.5) + concurrent-ruby (~> 1.0) + warden (1.2.9) + rack (>= 2.0.9) + web-console (4.2.0) + actionview (>= 6.0.0) + activemodel (>= 6.0.0) + bindex (>= 0.4.0) + railties (>= 6.0.0) + webdrivers (5.2.0) + nokogiri (~> 1.6) + rubyzip (>= 1.3.0) + selenium-webdriver (~> 4.0) + websocket (1.2.9) + websocket-driver (0.7.5) + websocket-extensions (>= 0.1.0) + websocket-extensions (0.1.5) + xpath (3.2.0) + nokogiri (~> 1.8) + zeitwerk (2.6.6) + +PLATFORMS + x86_64-linux + +DEPENDENCIES + bootsnap + bootstrap (~> 5.2.2) + capybara + debug + devise + importmap-rails + jbuilder + puma (~> 5.0) + rails (~> 7.0.4) + rails-controller-testing + selenium-webdriver + sprockets-rails + sqlite3 (~> 1.4) + stimulus-rails + turbo-rails + tzinfo-data + web-console + webdrivers + +RUBY VERSION + ruby 3.0.5p211 + +BUNDLED WITH + 2.2.33 diff --git a/week_5/activity-tracker/README.md b/week_5/activity-tracker/README.md new file mode 100644 index 00000000..d97ac306 --- /dev/null +++ b/week_5/activity-tracker/README.md @@ -0,0 +1,262 @@ +# Controllers | Activity Tracker + +Alright! We have our model (which we will use to represent our data) ready to go. Now what we need to do is somehow be able to use this data to display content on our web app. + +Before we go into what controllers are, lets briefly look into what happens when a request is made to a Rails application. + +## Request Response Cycle +_(This is an oversimplification of the processes that happen under the hood. To know more details about what happens, you can refer to any resource about request-response cycle online.)_ + +The first thing that you would do is open up your browser, and enter a URL. Then some magic happens, and you can see the output webpage. Right? + +What happens internally is, every URL is mapped to a particular controller action. It is the controller's function to take over control, and fetch any necessary data it needs from database (via models that you made during the last week. Nice!). +This data is then packaged in appropriate formats - for example, if you are making an API server, your response would probably be in the JSON format. + +For a regular Rails app, the data from the controller is passed on the the special HTML pages, called _views_. In the views, you define how your data should be presented to the user. + +## Steps + +So lets recap. For making the web application work, we need: +- URLs. Each one of these are mapped to particular controller actions. +- Controllers. They aggregate all information needed for display, and pass it to the views. +- Views. They are what you see as the response. + +Quite a lot of steps right? Well, you're lucky you're learning Rails. + +## Scaffolding +There is a lot of "magic" that Rails does to make the developer's life much easier. One of the greatest ways, and very powerful tool that you'll be using often, is **scaffolds**. + +A scaffold basically does what it says - creates a lot of boilerplate code, so that you don't have to manually type it out. What is this boilerplate you ask? + +The scaffold operation creates the model, controller, views, routes and associated test files for the object that you specify. The URLs and controller actions that are made are the ones commonly used for CRUD operations - creating, removing, updating and deleting records. + +If it seems a little overwhelming to you right now, fear not! All shall be revealed soon. + +## Requirement +As a small recap, this is the data that we need in our application. + +- Title: `string` +- ActivityType: `string` +- Start: `datetime` +- Duration: `decimal` +- Calories: `integer` + +In the previous week, you might have generated the model for this using `rails generate model`. This time, we'll create a scaffold for this. + +```shell +rails generate scaffold Activity title:string activity_type:string start:datetime duration:decimal calories:integer +``` + +Make sure you keep in mind the Rails naming conventions! They apply here also. + +When you run this command, a ton of files would have been generated on your system. Lets take an overview of the files generated. + +- `create db/migrate/20230127173852_create_activities.rb`: Creating the migration file, to be applied to the database. +- `create app/models/activity.rb0`: The model file for our model. +- `create test/models/activity_test.rb`: Test file, for writing tests. +- `route resources :activities`: Routes (URLs). Add the basic CRUD URLs automatically. +- `create app/controllers/activities_controller.rb`: Controller. This is where you write controller actions. +- `create app/views/activities/*`: A bunch of files in this directory. These correspond to the views that will be rendered. +- `create test/controllers/activities_controller_test.rb`: Test suite for the controller. +- `create app/helpers/activities_helper.rb`: Helper for our resource. + +Ensure that you have created the database using `rails db:create`. You can now apply migrations created by using `rails db:migrate`. + +Run the server using `rails server`. If you now go to `localhost:3000/activities` on your browser, you can see a basic app in function! + +image + +Feel free to play around with the app now. Here are some screenshots of what you should be able to see: + +image + +_New Activity_ + +image + +_Show activity_ + +image + +_Editing an activity_ + + +## The Controller +Now, lets open the controller and see what is happening. We'll take an example of a simple function, and try to understand what is happening. + +```ruby + def index + @activities = Activity.all + end +``` + +This is the `index` function. As the name suggests, this is the controller action that is called when you go to the home page. It displays a list of all the available entries for you to view (i.e. it provides an "index" of all data.) + +`Activity` refers to our model. The all function allows us to pick up all the entries that are stored as part of the `Activity` model, that is, all rows in the activities table. We save that in a variable called `@activities`. + +If you notice, the variable starts with `@`. This is a special type of variable in Rails, known as **instance variables**. These are variables that are accessible in both the controller and the views. + +At the end, we do not tell Rails to render any particular template (in opposition to some other frameworks, for instance Django). This is because of how Rails works - convention over configuration. Rails will automatically look for a file with the name `index.html` or `index.html.erb` (you'll learn about the `.erb` format when you learn about views), and directly render that file. +Pretty convenient, right? + +### Other important actions + +- `before_action`: A callback that sets the @activity instance variable with the Activity model instance, based on the id passed in the URL, before executing show, edit, update, and destroy actions. + +- `show` action: Displays the information of a single Activity instance, stored in the @activity instance variable. (GET Request) + +- `new` action: Creates a new instance of the Activity model, stored in the @activity instance variable. (GET Request) + +- `edit` action: Edits an existing Activity instance, stored in the @activity instance variable. (GET Request) + +- `create` action: Creates a new Activity instance with the parameters passed from the form, stored in the @activity instance variable. If the save is successful, it redirects to the show view with a success message, otherwise it renders the new view with an error message. (POST Request) + +```ruby + + def create + @activity = Activity.new(activity_params) + + respond_to do |format| + if @activity.save + format.html { redirect_to activity_url(@activity), notice: "Activity was successfully created." } + format.json { render :show, status: :created, location: @activity } + else + format.html { render :new, status: :unprocessable_entity } + format.json { render json: @activity.errors, status: :unprocessable_entity } + end + end + end + +``` + +- `update` action: Updates an existing Activity instance with the parameters passed from the form, stored in the @activity instance variable. If the update is successful, it redirects to the show view with a success message, otherwise it renders the edit view with an error message. (PUT/PATCH Request) + +```ruby + + def update + respond_to do |format| + if @activity.update(activity_params) + format.html { redirect_to activity_url(@activity), notice: "Activity was successfully updated." } + format.json { render :show, status: :ok, location: @activity } + else + format.html { render :edit, status: :unprocessable_entity } + format.json { render json: @activity.errors, status: :unprocessable_entity } + end + end + end + +``` + +- `destroy` action: Destroys an existing Activity instance, stored in the @activity instance variable. It then redirects to the index view with a success message. (DELETE Request) + +```ruby + + def destroy + @activity.destroy + + respond_to do |format| + format.html { redirect_to activities_url, notice: "Activity was successfully destroyed." } + format.json { head :no_content } + end + end + +``` + +- `set_activity` private method: Sets the @activity instance variable based on the id passed in the URL. + +- `activity_params` private method: Strong parameters method, allows only the title, activity_type, start, duration, and calories attributes to be passed as parameters to the Activity model. + +image + + +## Looking at the logs + +Logs are useful to debug the application and display information about what is happening (as they 'log' everything). They can be viewed in the terminal where you ran `rails server`. + +Lets understand one such log. Others follow a similar pattern and can be explored on your own. + +image + +This is generated when you try to edit an activity. + +- The first line indicates that it has started the "PATCH" method for the _route_ `/activites/1`. + +- Processing by `ActivitiesController#update` indicates that the request is being processed by the `ActivitiesController`'s `update` action. + +- The next line indicates all the paramters being passed. This is the body of an HTTP Request. It contains all the information of our activity. + +- `set_activity` is run as a before action to find the mathing activity. + +- `UPDATE "activities" SET "calories" = ?....` indicates that an SQL `UPDATE` query is run to update our activity in the database. + +- `Redirected to https://mittal-parth-zany-space-engine-6pvjx5rjx743pwp-3000.preview.app.github.dev/activities/1` indicates that after successful updation of the record, the user has been redirected to `/activities/1` (showing the activity) + +- `Completed 302` indicates the status code of the response. 302 as you'd recall stands for redirect. + +## `rails generate controller` +Scaffolding is an extremely easy and powerful way to bring up your resources. However, this is not the only way you can create controllers. +They can also be generated normally by + +```shell +rails generate controller NAME [action action] [options] +``` + +Using this, you can create your own controllers as well. They do not have to be always bound to a particular model +and can exist independently as well. + +## Routing +Now, we have all the CRUD URLs by default for us, thanks to scaffold. Let's dig a bit deeper into how routes works. +Open up `config/routes.rb`. Your file will look something like this: + +```ruby +Rails.application.routes.draw do + resources :activities + # Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html + + # Defines the root path route ("/") + # root "articles#index" +end + +``` + +This is the file where all routes for the application are defined. Whenever the server receives a request, it searches among this list of routes and controller action mappings to find what to do with the request. +Note the second line: + +```ruby +resources :activities +``` + +This is what generates all the CRUD operations on that model. In general, if you have a model, you can add all the CRUD operations by using `resources :NAME` without having to individually define routes. + +However, sometimes we need other routes too, and not just these basic ones. An example is the following: + +```ruby + get 'about', to: "pages#about" +``` + +This tells Rails to dispatch a GET request to `/about` to the `about` action of the `Pages` controller. The generic format is `GET/POST/etc 'route', to: 'controller#action'` + +But what if you wanted an additional route on your resource? Lets say you wanted the following routes: +- `/activity/load`: to load some activity data from another file. +- `/activity/:id/share`: to share your activity with friends. + +You could write these routes similar to the previous way; where you explicitly define the entire route. However, for URLs that add to resources, there is a better way. + +```ruby +resources :activities do + member do + get 'share' # GET /activity/:id/share + end + collection do + get 'load' # GET /activities/load + end +end +``` + +`member` adds the route to every individual record of that item, making routes that contain the ID of the item. `collection` adds the route to the entire collection, and so there are no IDs to the URL. +Not providing `to:` will tell Rails to look for a action with the same name as the URL, in the controller for that model. + +## References +- [Rails Routing from the Outside In](https://guides.rubyonrails.org/routing.html) +- [Action Controllers](https://guides.rubyonrails.org/action_controller_overview.html) +- [Layouts and Rendering in Rails (Views)](https://guides.rubyonrails.org/layouts_and_rendering.html) diff --git a/week_5/activity-tracker/Rakefile b/week_5/activity-tracker/Rakefile new file mode 100644 index 00000000..9a5ea738 --- /dev/null +++ b/week_5/activity-tracker/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/week_5/activity-tracker/app/assets/config/manifest.js b/week_5/activity-tracker/app/assets/config/manifest.js new file mode 100644 index 00000000..ddd546a0 --- /dev/null +++ b/week_5/activity-tracker/app/assets/config/manifest.js @@ -0,0 +1,4 @@ +//= link_tree ../images +//= link_directory ../stylesheets .css +//= link_tree ../../javascript .js +//= link_tree ../../../vendor/javascript .js diff --git a/week_5/activity-tracker/app/assets/images/.keep b/week_5/activity-tracker/app/assets/images/.keep new file mode 100644 index 00000000..e69de29b diff --git a/week_5/activity-tracker/app/assets/stylesheets/application.scss b/week_5/activity-tracker/app/assets/stylesheets/application.scss new file mode 100644 index 00000000..addd78cb --- /dev/null +++ b/week_5/activity-tracker/app/assets/stylesheets/application.scss @@ -0,0 +1,16 @@ +/* + * This is a manifest file that'll be compiled into application.css, which will include all the files + * listed below. + * + * Any CSS (and SCSS, if configured) file within this directory, lib/assets/stylesheets, or any plugin's + * vendor/assets/stylesheets directory can be referenced here using a relative path. + * + * You're free to add application-wide styles to this file and they'll appear at the bottom of the + * compiled file so the styles you add here take precedence over styles defined in any other CSS + * files in this directory. Styles in this file should be added after the last require_* statement. + * It is generally better to create a new file per style scope. + * + *= require_tree . + *= require_self + */ +@import "bootstrap"; \ No newline at end of file diff --git a/week_5/activity-tracker/app/assets/stylesheets/dark-mode.css b/week_5/activity-tracker/app/assets/stylesheets/dark-mode.css new file mode 100644 index 00000000..09585cc5 --- /dev/null +++ b/week_5/activity-tracker/app/assets/stylesheets/dark-mode.css @@ -0,0 +1,900 @@ +:root { + --primary: #49c195; + --secondary: #565d63; + --success: #216a48; + --info: #0e4c66; + --warning: #6d5911; + --danger: #721326; + --focus: #2a2732; + --alternate: #4c3057; + + /* Borders are a slightly darker version of the color... */ + --primary-border: #349672; + --secondary-border: #40444b; + --success-border: #1a573a; + --info-border: #0a384b; + --warning-border: #55450d; + --danger-border: #550e1d; + --focus-border: #16161c; + --alternate-border: #382442; + + /* while text is lighter... */ + --primary-text: #45FFBC; + --secondary-text: #98a2ac; + --success-text: #35a771; + --info-text: #1782b1; + --warning-text: #b8941d; + --danger-text: #af1e3b; + --focus-text: #887fa5; + --alternate-text: #9763af; + + --table-border: #424242; + --table-hover: #1c1d38; + + --text: #fff; + --text-disabled: #aaa; + --placeholder-text: #bbbbbb; + + --switchery-background: #7f7f7f; + --loader-img: #1a1a1a; + + --form-control-bg: #202020; + --form-control-border: #1a1a1a; + --primary-checkbox: #4c5093; + + --toggle-dark-mode-text: #ffffff; + --profile-update-detail: #582e2e; +} + +/* Placeholder for input */ +::-webkit-input-placeholder { + /* WebKit, Blink, Edge */ + color: var(--placeholder-text) !important; +} + +:-moz-placeholder { + /* Mozilla Firefox 4 to 18 */ + color: var(--placeholder-text) !important; + opacity: 1; +} + +::-moz-placeholder { + /* Mozilla Firefox 19+ */ + color: var(--placeholder-text) !important; + opacity: 1; +} + +:-ms-input-placeholder { + /* Internet Explorer 10-11 */ + color: var(--placeholder-text) !important; +} + +::-ms-input-placeholder { + /* Microsoft Edge */ + color: var(--placeholder-text) !important; +} + +::placeholder { + /* Most modern browsers support this now. */ + color: var(--placeholder-text) !important; +} + +input { + color: var(--text) !important; + background: var(--form-control-bg); + border: 1px solid var(--form-control-border); +} + +/* Text color */ +body { + color: var(--text); + background: #000; +} + +a { + /* TODO: Change link colors */ + color: white !important; +} + +.text-primary { + color: var(--primary-text) !important; +} + +.text-secondary { + color: var(--secondary-text) !important; +} + +.text-alternate { + color: var(--alternate-text) !important; +} + +/* Top Bar */ +.bg-royal { + background-image: linear-gradient(to right, #1b1b1b, #000000) !important; +} + +/* Title-Nav Bar */ +.app-theme-gray .app-header { + background: #1a1a1a; + -webkit-box-shadow: -1px 14px 44px -4px rgba(0, 0, 0, 0.65); + -moz-box-shadow: -1px 14px 44px -4px rgba(0, 0, 0, 0.65); + box-shadow: -1px 14px 44px -4px rgba(0, 0, 0, 0.65); +} + +.horizontal-nav-menu>li>a span::before { + background: var(--primary); +} + +.app-theme-gray .app-page-title { + border-bottom: none; +} + +.header-mobile-open { + background: #1a1a1a; + border-color: #151515; +} + +/* IRIS LOGO */ +.app-header__logo { + background: var(--primary); +} + +/* Page Title -- Bread crumb Bar */ +.app-theme-gray .app-page-title { + background: #1a1a1a; +} + +.app-page-title .page-title-wrapper::before { + background: var(--primary); +} + +/* show/hide menu bar */ +.app-theme-gray .app-inner-bar { + background: #262626; + border-bottom: none; +} + +/* menu */ +.dropdown-menu { + background-color: #262626; +} + +.header-mobile-open .horizontal-nav-menu { + background-color: #212121; +} + +.header-mobile-open .horizontal-nav-menu>li { + border-color: #1f1f1f; +} + +/* side bar color */ +.app-inner-layout__sidebar { + background: #1e1e1e !important; + color: white; +} + +.dropdown-item { + color: white; +} + +.dropdown-item:hover, +.dropdown-item:focus { + color: #fff; + background: var(--primary-border); +} + +.dropdown-item.active, +.dropdown-item:active { + color: #fff; + text-decoration: none; + background-color: var(--primary); +} + +.app-inner-layout.app-inner-layout-page .app-inner-layout__wrapper .app-inner-layout__sidebar { + border-right: none; +} + +.app-main__inner { + background: #1a1a1a; +} + +/* content body */ +.app-inner-layout__wrapper { + background: #1a1a1a; +} + +/* HEADER */ + +.header-btn-lg::before { + background: #474747; +} + +.grid-menu [class*="col-"] { + border-right: #474747 solid 0; + border-bottom: #474747 solid 1px; +} + +.nav-item.nav-item-header { + color: var(--secondary-text); +} + +.divider { + background: #474747; +} + +/* When scrolling up to the top, a small bar or 2 appears. Color of bar is this */ +.app-theme-gray.app-container { + background: rgb(26, 26, 26); +} + +/* FOOTER */ +.app-wrapper-footer .app-footer { + border: none; +} + +.app-theme-gray .app-footer { + background: #131313; +} + +.footer-dots .dots-separator { + background: #474747; +} + +.list-group-item { + background-color: transparent; +} + +.border-light { + border-color: #2a2a2a !important; +} + +.widget-numbers { + color: var(--text); +} + +/* FORMS */ + +select { + background-color: var(--form-control-bg); + border-color: var(--form-control-border); + color: var(--text); +} + +.form-control { + background: var(--form-control-bg); + border-color: var(--form-control-border); + color: white; +} + +.form-control:focus { + background-color: #2f2f2f; + border-color: #349672; + color: white; +} + +.form-control:disabled, +.form-control[readonly] { + background-color: #292929 !important; +} + +.input-group-text { + background-color: #262626; + border: 1px solid #1f1f1f; + color: white; +} + +.custom-select { + color: var(--text); + background-color: #333333; + border-color: var(--form-control-border); +} + +.custom-select:focus { + border-color: var(--form-control-border); + box-shadow: 0 0 0 0.2rem #222; +} + +.custom-control-label::before { + background-color: #333333; + border-color: var(--form-control-border); +} + +.custom-control-input:checked~.custom-control-label::before { + background-color: var(--primary-checkbox); + border-color: var(--primary-border); +} + +/* Progress Bar */ + +.progress { + background-color: transparent; +} + +.progress-bar { + background-color: var(--primary); +} + +/* Select2 */ + +.select2-container--bootstrap4 .select2-selection { + background-color: var(--form-control-bg); + border: 1px solid #1a1a1a; + color: white !important; +} + +.select2-container--bootstrap4 .select2-selection--single .select2-selection__rendered { + color: white; + padding: 0; +} + +.select2-container--open .select2-dropdown { + color: #fff; + background-color: #262626; +} + +.select2-container--bootstrap4 .select2-results__option[aria-selected=true] { + background-color: var(--primary); + color: #fff; +} + +.select2-container--bootstrap4 .select2-results__option--highlighted[aria-selected] { + background-color: var(--primary); +} + +.select2-container--bootstrap4 .select2-search--dropdown .select2-search__field { + background-color: var(--form-control-bg); + border-color: #1a1a1a; + color: #fff; +} + +.select2-container--bootstrap4 .select2-selection--multiple .select2-selection__choice { + background-color: #333131; + border-color: #1a1a1a; + color: #fff; +} + +.select2-container--bootstrap4.select2-container--focus .select2-selection, +.select2-container--bootstrap4.select2-container--open .select2-selection { + border-color: #1a1a1a; +} + +/* Daterangepicker */ + +.daterangepicker { + color: var(--text); +} + +.daterangepicker .calendar-table { + background-color: #262626; + border: #232323; +} + +.daterangepicker td.off, +.daterangepicker td.off.in-range, +.daterangepicker td.off.start-date, +.daterangepicker td.off.end-date { + background-color: #202020; + color: var(--text-disabled); +} + +.daterangepicker td.active, +.daterangepicker td.active:hover { + background-color: var(--primary); +} + +.daterangepicker td.available:hover, +.daterangepicker th.available:hover { + background-color: var(--primary); +} + +.daterangepicker select.hourselect, +.daterangepicker select.minuteselect, +.daterangepicker select.secondselect, +.daterangepicker select.ampmselect { + background-color: var(--form-control-bg); + border-color: var(--form-control-border); +} + +/* FullCalendar */ + +.fc-state-active { + background-color: #464646 !important; + color: #fff !important; +} + +/* Tooltip */ + +.popover-body { + background: #262626; + color: #fff; +} + +.bs-popover-right .arrow::after, +.bs-popover-auto[x-placement^="right"] .arrow::after { + border-right-color: #262626; +} + +.ui-widget.ui-widget-content { + border-color: #232323; +} + +.ui-widget-content { + border-color: #232323; + background: #262626; + color: var(--text); +} + +.ui-widget-shadow { + -webkit-box-shadow: 0px 0px 5px #222; + box-shadow: 0px 0px 5px #222; +} + +/* CARD STYLES */ +.card { + background-color: #272727; + box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19); + background: #272727; + background: -webkit-linear-gradient(to bottom, #272727, #3c3c3c); + background: linear-gradient(to bottom, #272727, #3c3c3c); +} + +.card-body { + background: #272727; + color: white; + position: relative; + display: flex; + flex-direction: column; + min-width: 0; + word-wrap: break-word; + background-clip: border-box; + border: 1px solid rgba(0, 0, 0, 0.15); + border-radius: 0.25rem; +} + +.card-deck { + display: flex; + flex-direction: column; +} + +.card-deck .card { + margin-bottom: 15px; +} + +@media (min-width: 576px) { + .card-deck { + flex-flow: row wrap; + margin-right: -15px; + margin-left: -15px; + } + .card-deck .card { + display: flex; + flex: 1 0 0%; + flex-direction: column; + margin-right: 15px; + margin-bottom: 15px; + margin-left: 15px; + } +} + +.ui-widget-header { + border: 1px solid #1f1f1f; + background: #262626; + color: #fff; + font-weight: bold; +} + +.card-header { + background: #212121 !important; + color: white; +} + +.card-header>.nav .nav-link.active { + color: var(--primary); +} + +.card-footer { + background: #212121 !important; + color: white; +} + +.card-title { + color: rgba(76, 95, 248, 0.6); +} + +.card-subtitle { + color: rgb(111, 118, 219); +} + +/* MODAL STYLES */ + +.modal-body { + background: #2d2d2d; + color: white; +} + +.modal-content { + background-color: #2d2d2d; + border: none; +} + +.modal-header { + background: #262626 !important; + border-bottom: 1px solid #1f1f1f; + color: white; +} + +.modal-footer { + background: #262626 !important; + border-top: 1px solid #1f1f1f; + color: white; +} + +.modal-dialog { + box-shadow: 0 0.76875rem 2.4875rem rgb(20 20 20 / 30%), 0 1.3375rem 1.70625rem rgb(20 20 20 / 30%), 0 0.55rem 0.53125rem rgb(0 0 0 / 5%), 0 0.225rem 0.4375rem rgb(20 20 20 / 30%); + border-radius: 0.25rem; +} + +.card-title { + color: rgba(76, 95, 248, 0.6); +} + +.card-subtitle { + color: rgb(111, 118, 219); +} + + +/* BUTTON STYLES */ + +.btn { + color: white; +} + +.btn-light { + background-color: #2f2f2f; + border-color: #242424; +} + +.btn-light.btn-shadow:hover { + box-shadow: 0 0.125rem 0.625rem #262626, 0 0.0625rem 0.125rem #262626; +} + +.btn-light:hover, +.btn-light:focus, +.btn-light:active { + background-color: #363636; + border-color: #1c1c1c; + color: #fff; +} + +.btn-light.btn-shadow { + box-shadow: 0 0.125rem 0.625rem #262626, 0 0.0625rem 0.125rem #262626; +} + +.btn-primary { + background-color: var(--primary); + border-color: var(--primary-border); +} + +.btn-primary:hover { + background-color: var(--primary-border); + border-color: var(--primary); +} + +.btn-secondary { + background-color: var(--secondary); + border-color: var(--secondary-border); +} + +.btn-success { + background-color: var(--success); + border-color: var(--success-border); +} + +.btn-info { + background-color: var(--info); + border-color: var(--info-border); +} + +.btn-warning { + background-color: var(--warning); + border-color: var(--warning-border); +} + +.btn-danger { + background-color: var(--danger); + border-color: var(--danger-border); +} + +.btn-focus { + background-color: var(--focus); + border-color: var(--focus-border); +} + +.btn-alternate { + background-color: var(--alternate); + border-color: var(--alternate-border); +} + +.btn-outline-primary { + border-color: var(--primary-border); +} + +.btn-outline-secondary { + border-color: var(--secondary-border); +} + +.btn-outline-success { + border-color: var(--success-border); +} + +.btn-outline-info { + border-color: var(--info-border); +} + +.btn-outline-warning { + border-color: var(--warning-border); +} + +.btn-outline-danger { + border-color: var(--danger-border); +} + +/* Bootstrap Alerts */ + +.alert { + color: #ffffff !important; +} + +.alert-primary { + background-color: var(--primary); + border-color: var(--primary-border); +} + +.alert-success { + background-color: var(--success); + border-color: var(--success-border); +} + +.alert-info { + background-color: var(--info); + border-color: var(--info-border); +} + +.alert-warning { + background-color: var(--warning); + border-color: var(--warning-border); +} + +.alert-danger { + color: #fff; + background-color: var(--danger); + border-color: var(--danger-border); +} + +.close { + color: #fff; +} + +.close:hover { + color: inherit; +} + +/* bootstrap backgrounds */ + + +.bg-primary { + background-color: var(--primary) !important; +} + +.bg-secondary { + background-color: var(--secondary) !important; +} + +.bg-success { + background-color: var(--success) !important; +} + +.bg-info { + background-color: var(--info) !important; +} + +.bg-warning { + background-color: var(--warning) !important; +} + +.bg-danger { + background-color: var(--danger) !important; +} + +.bg-focus { + background-color: var(--focus) !important; +} + +.bg-alternate { + background-color: var(--alternate) !important; +} + +/* Bootstrap Badges */ + +.badge-primary { + background-color: var(--primary); +} + +.badge-secondary { + background-color: var(--secondary); +} + +.badge-info { + background-color: var(--info); +} + +.badge-success { + background-color: var(--success); +} + +.badge-warning { + background-color: var(--warning); +} + +.badge-danger { + background-color: var(--danger); +} + +/* TABLE */ + +tr { + border-color: var(--table-border); +} + +.table thead th { + vertical-align: bottom; + border-color: var(--table-border); + background: #1f1f1f; +} + +.table tbody tr { + background: #242424; +} + +.table-bordered th, +.table-bordered td { + border-color: var(--table-border); +} + +.table-striped tbody tr:nth-child(odd) { + background-color: #212121 !important; +} + +.table { + border-color: var(--table-border); +} + +.table-hover tbody tr:hover { + background-color: var(--table-hover) !important; +} + +.table-primary { + background-color: var(--primary); +} + +.table-primary:hover { + background-color: var(--primary-border) !important; +} + +.table th, +.table td { + border-color: var(--table-border); +} + +/* Datatable */ + +/* pagination buttons (selected) */ +.pagination li a { + color: var(--primary); + background-color: #383838; + border: 1px solid #262626; +} + +/*other pagination buttons*/ +.page-item.disabled .page-link, +.pagination .disabled.page-number .page-link { + color: var(--text-disabled) !important; + background-color: #383838; + border-color: #262626; +} + +.pagination li a:hover { + background-color: #555555; + border-color: #262626; +} + +.pagination li.disabled a { + background-color: #383838; + border-color: #262626; +} + +.page-item.active .page-link, +.pagination .active.page-number .page-link { + background-color: var(--primary); + border-color: var(--primary-border); +} + +/* Copy button */ +div.dt-button-info { + background-color: #212121 !important; + border-color: #111 !important; + box-shadow: 3px 3px 8px rgba(0, 0, 0, 0.3); +} + +div.dt-button-info h2 { + border-color: #1a1a1a !important; + background-color: #262626 !important; +} + +/* Dashboard Buttons */ + +/* TODO: Add transparent background dashboard images before uncommenting */ +/*.option_buttons {*/ +/* border-color: #444 !important;*/ +/*}*/ + +/*.button-label {*/ +/* color: var(--text) !important;*/ +/*}*/ + +/*DARK MODE TOGGLE */ +.toggle-link, +.toggle-link:active, +.toggle-link:focus { + color: #fff; +} + +/* Miscalleneous */ + +.tabs-animated .nav-link::before { + background-color: var(--primary); +} + +.tabs-animated-shadow .nav-link::before { + box-shadow: 0 16px 26px -10px var(--primary-border), 0 4px 25px 0px rgba(0, 0, 0, 0.12), 0 8px 10px -5px rgba(31, 36, 64, 0.2); +} + +.font-icon-wrapper { + border-color: var(--table-border); +} + +.font-icon-wrapper:hover { + color: transparent; +} + + +.toggle-handle, +.toggle-handle:hover { + background-color: var(--switchery-background); +} + +/* jQuery TagsInput */ +[data-theme="dark"] div.tagsinput { + border: 1px solid var(--form-control-border) !important; + background: var(--form-control-bg) !important; + padding: 5px; + width: 300px; + height: 100px; + overflow-y: auto; +} + +[data-theme="dark"] div.tagsinput span.tag { + border: 1px solid #a5d24a; + -moz-border-radius: 2px; + -webkit-border-radius: 2px; + display: block; + float: left; + padding: 5px; + text-decoration: none; + background: #a0db2d !important; + color: #341 !important; + margin-right: 5px; + margin-bottom: 5px; + font-family: helvetica; + font-size: 13px; +} \ No newline at end of file diff --git a/week_5/activity-tracker/app/channels/application_cable/channel.rb b/week_5/activity-tracker/app/channels/application_cable/channel.rb new file mode 100644 index 00000000..d6726972 --- /dev/null +++ b/week_5/activity-tracker/app/channels/application_cable/channel.rb @@ -0,0 +1,4 @@ +module ApplicationCable + class Channel < ActionCable::Channel::Base + end +end diff --git a/week_5/activity-tracker/app/channels/application_cable/connection.rb b/week_5/activity-tracker/app/channels/application_cable/connection.rb new file mode 100644 index 00000000..0ff5442f --- /dev/null +++ b/week_5/activity-tracker/app/channels/application_cable/connection.rb @@ -0,0 +1,4 @@ +module ApplicationCable + class Connection < ActionCable::Connection::Base + end +end diff --git a/week_5/activity-tracker/app/controllers/activities_controller.rb b/week_5/activity-tracker/app/controllers/activities_controller.rb new file mode 100644 index 00000000..a1dc90c1 --- /dev/null +++ b/week_5/activity-tracker/app/controllers/activities_controller.rb @@ -0,0 +1,70 @@ +class ActivitiesController < ApplicationController + before_action :set_activity, only: %i[ show edit update destroy ] + + # GET /activities or /activities.json + def index + @activities = Activity.all + end + + # GET /activities/1 or /activities/1.json + def show + end + + # GET /activities/new + def new + @activity = Activity.new + end + + # GET /activities/1/edit + def edit + end + + # POST /activities or /activities.json + def create + @activity = Activity.new(activity_params) + + respond_to do |format| + if @activity.save + format.html { redirect_to activity_url(@activity), notice: "Activity was successfully created." } + format.json { render :show, status: :created, location: @activity } + else + format.html { render :new, status: :unprocessable_entity } + format.json { render json: @activity.errors, status: :unprocessable_entity } + end + end + end + + # PATCH/PUT /activities/1 or /activities/1.json + def update + respond_to do |format| + if @activity.update(activity_params) + format.html { redirect_to activity_url(@activity), notice: "Activity was successfully updated." } + format.json { render :show, status: :ok, location: @activity } + else + format.html { render :edit, status: :unprocessable_entity } + format.json { render json: @activity.errors, status: :unprocessable_entity } + end + end + end + + # DELETE /activities/1 or /activities/1.json + def destroy + @activity.destroy + + respond_to do |format| + format.html { redirect_to activities_url, notice: "Activity was successfully destroyed." } + format.json { head :no_content } + end + end + + private + # Use callbacks to share common setup or constraints between actions. + def set_activity + @activity = Activity.find(params[:id]) + end + + # Only allow a list of trusted parameters through. + def activity_params + params.require(:activity).permit(:title, :activity_type, :start, :duration, :calories) + end +end diff --git a/week_5/activity-tracker/app/controllers/application_controller.rb b/week_5/activity-tracker/app/controllers/application_controller.rb new file mode 100644 index 00000000..6b4dcfa8 --- /dev/null +++ b/week_5/activity-tracker/app/controllers/application_controller.rb @@ -0,0 +1,3 @@ +class ApplicationController < ActionController::Base + before_action :authenticate_user! +end diff --git a/week_5/activity-tracker/app/controllers/concerns/.keep b/week_5/activity-tracker/app/controllers/concerns/.keep new file mode 100644 index 00000000..e69de29b diff --git a/week_5/activity-tracker/app/controllers/home_controller.rb b/week_5/activity-tracker/app/controllers/home_controller.rb new file mode 100644 index 00000000..a2381f3f --- /dev/null +++ b/week_5/activity-tracker/app/controllers/home_controller.rb @@ -0,0 +1,6 @@ +class HomeController < ApplicationController + skip_before_action :authenticate_user!, only: %i[index] + def index + end + +end diff --git a/week_5/activity-tracker/app/controllers/stats_controller.rb b/week_5/activity-tracker/app/controllers/stats_controller.rb new file mode 100644 index 00000000..5ea249bd --- /dev/null +++ b/week_5/activity-tracker/app/controllers/stats_controller.rb @@ -0,0 +1,14 @@ +class StatsController < ApplicationController + + def index + @total_duration = 0 + @total_calorie = 0 + activities = Activity.all; + activities.each do |activity| + @total_duration += activity.duration + @total_calorie += activity.calories + end + end + +end + diff --git a/week_5/activity-tracker/app/helpers/activities_helper.rb b/week_5/activity-tracker/app/helpers/activities_helper.rb new file mode 100644 index 00000000..4e9784cc --- /dev/null +++ b/week_5/activity-tracker/app/helpers/activities_helper.rb @@ -0,0 +1,2 @@ +module ActivitiesHelper +end diff --git a/week_5/activity-tracker/app/helpers/application_helper.rb b/week_5/activity-tracker/app/helpers/application_helper.rb new file mode 100644 index 00000000..de6be794 --- /dev/null +++ b/week_5/activity-tracker/app/helpers/application_helper.rb @@ -0,0 +1,2 @@ +module ApplicationHelper +end diff --git a/week_5/activity-tracker/app/helpers/home_helper.rb b/week_5/activity-tracker/app/helpers/home_helper.rb new file mode 100644 index 00000000..23de56ac --- /dev/null +++ b/week_5/activity-tracker/app/helpers/home_helper.rb @@ -0,0 +1,2 @@ +module HomeHelper +end diff --git a/week_5/activity-tracker/app/helpers/stats_helper.rb b/week_5/activity-tracker/app/helpers/stats_helper.rb new file mode 100644 index 00000000..65e2f8bb --- /dev/null +++ b/week_5/activity-tracker/app/helpers/stats_helper.rb @@ -0,0 +1,2 @@ +module StatsHelper +end diff --git a/week_5/activity-tracker/app/javascript/application.js b/week_5/activity-tracker/app/javascript/application.js new file mode 100644 index 00000000..0d7b4940 --- /dev/null +++ b/week_5/activity-tracker/app/javascript/application.js @@ -0,0 +1,3 @@ +// Configure your import map in config/importmap.rb. Read more: https://github.com/rails/importmap-rails +import "@hotwired/turbo-rails" +import "controllers" diff --git a/week_5/activity-tracker/app/javascript/controllers/application.js b/week_5/activity-tracker/app/javascript/controllers/application.js new file mode 100644 index 00000000..1213e85c --- /dev/null +++ b/week_5/activity-tracker/app/javascript/controllers/application.js @@ -0,0 +1,9 @@ +import { Application } from "@hotwired/stimulus" + +const application = Application.start() + +// Configure Stimulus development experience +application.debug = false +window.Stimulus = application + +export { application } diff --git a/week_5/activity-tracker/app/javascript/controllers/hello_controller.js b/week_5/activity-tracker/app/javascript/controllers/hello_controller.js new file mode 100644 index 00000000..5975c078 --- /dev/null +++ b/week_5/activity-tracker/app/javascript/controllers/hello_controller.js @@ -0,0 +1,7 @@ +import { Controller } from "@hotwired/stimulus" + +export default class extends Controller { + connect() { + this.element.textContent = "Hello World!" + } +} diff --git a/week_5/activity-tracker/app/javascript/controllers/index.js b/week_5/activity-tracker/app/javascript/controllers/index.js new file mode 100644 index 00000000..54ad4cad --- /dev/null +++ b/week_5/activity-tracker/app/javascript/controllers/index.js @@ -0,0 +1,11 @@ +// Import and register all your controllers from the importmap under controllers/* + +import { application } from "controllers/application" + +// Eager load all controllers defined in the import map under controllers/**/*_controller +import { eagerLoadControllersFrom } from "@hotwired/stimulus-loading" +eagerLoadControllersFrom("controllers", application) + +// Lazy load controllers as they appear in the DOM (remember not to preload controllers in import map!) +// import { lazyLoadControllersFrom } from "@hotwired/stimulus-loading" +// lazyLoadControllersFrom("controllers", application) diff --git a/week_5/activity-tracker/app/jobs/application_job.rb b/week_5/activity-tracker/app/jobs/application_job.rb new file mode 100644 index 00000000..d394c3d1 --- /dev/null +++ b/week_5/activity-tracker/app/jobs/application_job.rb @@ -0,0 +1,7 @@ +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/week_5/activity-tracker/app/mailers/application_mailer.rb b/week_5/activity-tracker/app/mailers/application_mailer.rb new file mode 100644 index 00000000..3c34c814 --- /dev/null +++ b/week_5/activity-tracker/app/mailers/application_mailer.rb @@ -0,0 +1,4 @@ +class ApplicationMailer < ActionMailer::Base + default from: "from@example.com" + layout "mailer" +end diff --git a/week_5/activity-tracker/app/models/activity.rb b/week_5/activity-tracker/app/models/activity.rb new file mode 100644 index 00000000..a99f990d --- /dev/null +++ b/week_5/activity-tracker/app/models/activity.rb @@ -0,0 +1,2 @@ +class Activity < ApplicationRecord +end diff --git a/week_5/activity-tracker/app/models/application_record.rb b/week_5/activity-tracker/app/models/application_record.rb new file mode 100644 index 00000000..b63caeb8 --- /dev/null +++ b/week_5/activity-tracker/app/models/application_record.rb @@ -0,0 +1,3 @@ +class ApplicationRecord < ActiveRecord::Base + primary_abstract_class +end diff --git a/week_5/activity-tracker/app/models/concerns/.keep b/week_5/activity-tracker/app/models/concerns/.keep new file mode 100644 index 00000000..e69de29b diff --git a/week_5/activity-tracker/app/models/user.rb b/week_5/activity-tracker/app/models/user.rb new file mode 100644 index 00000000..47567994 --- /dev/null +++ b/week_5/activity-tracker/app/models/user.rb @@ -0,0 +1,6 @@ +class User < ApplicationRecord + # Include default devise modules. Others available are: + # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable + devise :database_authenticatable, :registerable, + :recoverable, :rememberable, :validatable +end diff --git a/week_5/activity-tracker/app/views/activities/_activity.html.erb b/week_5/activity-tracker/app/views/activities/_activity.html.erb new file mode 100644 index 00000000..804b3f6c --- /dev/null +++ b/week_5/activity-tracker/app/views/activities/_activity.html.erb @@ -0,0 +1,34 @@ + +
+

<%= activity.title %>

+
+
+
+
<%= activity.activity_type %>
+
+
+
+
+ <%= link_to "".html_safe, edit_activity_path(activity), class: "btn btn-sm btn-secondary" %> +
+
+ <%= button_to "".html_safe, activity, method: :delete, class: "btn btn-sm btn-secondary" %> +
+
+
+
+
+
+
<%= activity.start.in_time_zone.strftime("%d %b, %Y %I:%M %p") %>
+
+
+
+
+
<%= activity.calories %>
+
+
+
<%= activity.duration %>
+
+
+
+
diff --git a/week_5/activity-tracker/app/views/activities/_activity.json.jbuilder b/week_5/activity-tracker/app/views/activities/_activity.json.jbuilder new file mode 100644 index 00000000..8efbd331 --- /dev/null +++ b/week_5/activity-tracker/app/views/activities/_activity.json.jbuilder @@ -0,0 +1,2 @@ +json.extract! activity, :id, :title, :activity_type, :start, :duration, :calories, :created_at, :updated_at +json.url activity_url(activity, format: :json) diff --git a/week_5/activity-tracker/app/views/activities/_form.html.erb b/week_5/activity-tracker/app/views/activities/_form.html.erb new file mode 100644 index 00000000..b61cb5b9 --- /dev/null +++ b/week_5/activity-tracker/app/views/activities/_form.html.erb @@ -0,0 +1,55 @@ +
+
+
+ <%= form_with(model: activity) do |form| %> + <% if activity.errors.any? %> +
+

<%= pluralize(activity.errors.count, "error") %> prohibited this activity from being saved:

+ +
    + <% activity.errors.each do |error| %> +
  • <%= error.full_message %>
  • + <% end %> +
+
+ <% end %> + +
+ <%= form.label :title, style: "display: block" %> + <%= form.text_field :title, class: "form-control mt-2" %> +
+ +
+ <%= form.label :activity_type, style: "display: block" %> + <%= form.text_field :activity_type, class:"form-control mt-2" %> +
+ +
+ <%= form.label :start, style: "display: block" %> + <%= form.datetime_field :start, class:"form-control mt-2" %> +
+ +
+
+
+ <%= form.label :duration, style: "display: block" %> + <%= form.text_field :duration, class:"form-control mt-2" %> +
+
+
+
+ <%= form.label :calories, style: "display: block" %> + <%= form.number_field :calories, class:"form-control mt-2" %> +
+
+
+ + +
+ <%= form.submit class: "btn mt-2 btn-primary text-dark" %> +
+ <% end %> + +
+
+
diff --git a/week_5/activity-tracker/app/views/activities/edit.html.erb b/week_5/activity-tracker/app/views/activities/edit.html.erb new file mode 100644 index 00000000..b6009c16 --- /dev/null +++ b/week_5/activity-tracker/app/views/activities/edit.html.erb @@ -0,0 +1,5 @@ +
+

Edit Activity

+ <%= render "form", activity: @activity %> +
+
\ No newline at end of file diff --git a/week_5/activity-tracker/app/views/activities/index.html.erb b/week_5/activity-tracker/app/views/activities/index.html.erb new file mode 100644 index 00000000..8f8043f1 --- /dev/null +++ b/week_5/activity-tracker/app/views/activities/index.html.erb @@ -0,0 +1,15 @@ + +

<%= notice %>

+ +

+ Activities + <%= link_to "".html_safe, new_activity_path %> +

+ +
+ <% @activities.each do |activity| %> +
+ <%= render activity %> +
+ <% end %> +
diff --git a/week_5/activity-tracker/app/views/activities/index.json.jbuilder b/week_5/activity-tracker/app/views/activities/index.json.jbuilder new file mode 100644 index 00000000..865f89ee --- /dev/null +++ b/week_5/activity-tracker/app/views/activities/index.json.jbuilder @@ -0,0 +1 @@ +json.array! @activities, partial: "activities/activity", as: :activity diff --git a/week_5/activity-tracker/app/views/activities/new.html.erb b/week_5/activity-tracker/app/views/activities/new.html.erb new file mode 100644 index 00000000..2ddd6ffc --- /dev/null +++ b/week_5/activity-tracker/app/views/activities/new.html.erb @@ -0,0 +1,5 @@ +
+

New activity

+ <%= render "form", activity: @activity %> +
+
\ No newline at end of file diff --git a/week_5/activity-tracker/app/views/activities/show.html.erb b/week_5/activity-tracker/app/views/activities/show.html.erb new file mode 100644 index 00000000..42393a84 --- /dev/null +++ b/week_5/activity-tracker/app/views/activities/show.html.erb @@ -0,0 +1,3 @@ +

<%= notice %>

+ +<%= render @activity %> \ No newline at end of file diff --git a/week_5/activity-tracker/app/views/activities/show.json.jbuilder b/week_5/activity-tracker/app/views/activities/show.json.jbuilder new file mode 100644 index 00000000..a145d0a8 --- /dev/null +++ b/week_5/activity-tracker/app/views/activities/show.json.jbuilder @@ -0,0 +1 @@ +json.partial! "activities/activity", activity: @activity diff --git a/week_5/activity-tracker/app/views/home/index.html.erb b/week_5/activity-tracker/app/views/home/index.html.erb new file mode 100644 index 00000000..9c24026a --- /dev/null +++ b/week_5/activity-tracker/app/views/home/index.html.erb @@ -0,0 +1,12 @@ +

Welcome To Activity Tracker

+
+<% if user_signed_in? %> +
Logged in as : <%= current_user.email %>

+ <%= link_to "Activities", activities_path, class: "btn btn-primary" %>

+ <%= link_to "Stats", "/activities/stats", class: "btn btn-dark" %>

+ <%= button_to "Log out", destroy_user_session_path, method: :delete , class: "btn btn-light"%> +<% else %> +

Sign In To See Activities


+ <%= link_to "Sign In", new_user_session_path , :class => "btn btn-primary" %> + <%= link_to "Sign UP" , new_user_registration_path , :class => "btn btn-secondary" %> +<%end %> diff --git a/week_5/activity-tracker/app/views/layouts/application.html.erb b/week_5/activity-tracker/app/views/layouts/application.html.erb new file mode 100644 index 00000000..ef71373c --- /dev/null +++ b/week_5/activity-tracker/app/views/layouts/application.html.erb @@ -0,0 +1,28 @@ + + + + + ActivityTracker + + <%# %> + <%= csrf_meta_tags %> + <%= csp_meta_tag %> + + <%= stylesheet_link_tag "application", "data-turbo-track": "reload" %> + <%= stylesheet_link_tag "dark-mode", "data-turbo-track": "reload" %> + + + <%= javascript_importmap_tags %> + + + + +<%= render partial: 'shared/navbar' %> + + +
+ <%= yield %> +
+ + + diff --git a/week_5/activity-tracker/app/views/layouts/mailer.html.erb b/week_5/activity-tracker/app/views/layouts/mailer.html.erb new file mode 100644 index 00000000..cbd34d2e --- /dev/null +++ b/week_5/activity-tracker/app/views/layouts/mailer.html.erb @@ -0,0 +1,13 @@ + + + + + + + + + <%= yield %> + + diff --git a/week_5/activity-tracker/app/views/layouts/mailer.text.erb b/week_5/activity-tracker/app/views/layouts/mailer.text.erb new file mode 100644 index 00000000..37f0bddb --- /dev/null +++ b/week_5/activity-tracker/app/views/layouts/mailer.text.erb @@ -0,0 +1 @@ +<%= yield %> diff --git a/week_5/activity-tracker/app/views/shared/_navbar.html.erb b/week_5/activity-tracker/app/views/shared/_navbar.html.erb new file mode 100644 index 00000000..3b0b7559 --- /dev/null +++ b/week_5/activity-tracker/app/views/shared/_navbar.html.erb @@ -0,0 +1,15 @@ + + +
\ No newline at end of file diff --git a/week_5/activity-tracker/app/views/stats/index.html.erb b/week_5/activity-tracker/app/views/stats/index.html.erb new file mode 100644 index 00000000..0fe8f87a --- /dev/null +++ b/week_5/activity-tracker/app/views/stats/index.html.erb @@ -0,0 +1,12 @@ + + + +
+
+ Activities Stats +
+ +
diff --git a/week_5/activity-tracker/app/views/users/confirmations/new.html.erb b/week_5/activity-tracker/app/views/users/confirmations/new.html.erb new file mode 100644 index 00000000..4af186b2 --- /dev/null +++ b/week_5/activity-tracker/app/views/users/confirmations/new.html.erb @@ -0,0 +1,16 @@ +

Resend confirmation instructions

+ +<%= form_for(resource, as: resource_name, url: confirmation_path(resource_name), html: { method: :post }) do |f| %> + <%= render "users/shared/error_messages", resource: resource %> + +
+ <%= f.label :email %>
+ <%= f.email_field :email, autofocus: true, autocomplete: "email", value: (resource.pending_reconfirmation? ? resource.unconfirmed_email : resource.email) %> +
+ +
+ <%= f.submit "Resend confirmation instructions" %> +
+<% end %> + +<%= render "users/shared/links" %> diff --git a/week_5/activity-tracker/app/views/users/mailer/confirmation_instructions.html.erb b/week_5/activity-tracker/app/views/users/mailer/confirmation_instructions.html.erb new file mode 100644 index 00000000..dc55f64f --- /dev/null +++ b/week_5/activity-tracker/app/views/users/mailer/confirmation_instructions.html.erb @@ -0,0 +1,5 @@ +

Welcome <%= @email %>!

+ +

You can confirm your account email through the link below:

+ +

<%= link_to 'Confirm my account', confirmation_url(@resource, confirmation_token: @token) %>

diff --git a/week_5/activity-tracker/app/views/users/mailer/email_changed.html.erb b/week_5/activity-tracker/app/views/users/mailer/email_changed.html.erb new file mode 100644 index 00000000..32f4ba80 --- /dev/null +++ b/week_5/activity-tracker/app/views/users/mailer/email_changed.html.erb @@ -0,0 +1,7 @@ +

Hello <%= @email %>!

+ +<% if @resource.try(:unconfirmed_email?) %> +

We're contacting you to notify you that your email is being changed to <%= @resource.unconfirmed_email %>.

+<% else %> +

We're contacting you to notify you that your email has been changed to <%= @resource.email %>.

+<% end %> diff --git a/week_5/activity-tracker/app/views/users/mailer/password_change.html.erb b/week_5/activity-tracker/app/views/users/mailer/password_change.html.erb new file mode 100644 index 00000000..b41daf47 --- /dev/null +++ b/week_5/activity-tracker/app/views/users/mailer/password_change.html.erb @@ -0,0 +1,3 @@ +

Hello <%= @resource.email %>!

+ +

We're contacting you to notify you that your password has been changed.

diff --git a/week_5/activity-tracker/app/views/users/mailer/reset_password_instructions.html.erb b/week_5/activity-tracker/app/views/users/mailer/reset_password_instructions.html.erb new file mode 100644 index 00000000..d91e3e12 --- /dev/null +++ b/week_5/activity-tracker/app/views/users/mailer/reset_password_instructions.html.erb @@ -0,0 +1,8 @@ +z`

Hello <%= @resource.email %>!

+ +

Someone has requested a link to change your password. You can do this through the link below.

+ +

<%= link_to 'Change my password', edit_password_url(@resource, reset_password_token: @token) %>

+ +

If you didn't request this, please ignore this email.

+

Your password won't change until you access the link above and create a new one.

diff --git a/week_5/activity-tracker/app/views/users/mailer/unlock_instructions.html.erb b/week_5/activity-tracker/app/views/users/mailer/unlock_instructions.html.erb new file mode 100644 index 00000000..41e148bf --- /dev/null +++ b/week_5/activity-tracker/app/views/users/mailer/unlock_instructions.html.erb @@ -0,0 +1,7 @@ +

Hello <%= @resource.email %>!

+ +

Your account has been locked due to an excessive number of unsuccessful sign in attempts.

+ +

Click the link below to unlock your account:

+ +

<%= link_to 'Unlock my account', unlock_url(@resource, unlock_token: @token) %>

diff --git a/week_5/activity-tracker/app/views/users/passwords/edit.html.erb b/week_5/activity-tracker/app/views/users/passwords/edit.html.erb new file mode 100644 index 00000000..863ffbb2 --- /dev/null +++ b/week_5/activity-tracker/app/views/users/passwords/edit.html.erb @@ -0,0 +1,25 @@ +

Change your password

+ +<%= form_for(resource, as: resource_name, url: password_path(resource_name), html: { method: :put }) do |f| %> + <%= render "users/shared/error_messages", resource: resource %> + <%= f.hidden_field :reset_password_token %> + +
+ <%= f.label :password, "New password" %>
+ <% if @minimum_password_length %> + (<%= @minimum_password_length %> characters minimum)
+ <% end %> + <%= f.password_field :password, autofocus: true, autocomplete: "new-password" %> +
+ +
+ <%= f.label :password_confirmation, "Confirm new password" %>
+ <%= f.password_field :password_confirmation, autocomplete: "new-password" %> +
+ +
+ <%= f.submit "Change my password" %> +
+<% end %> + +<%= render "users/shared/links" %> diff --git a/week_5/activity-tracker/app/views/users/passwords/new.html.erb b/week_5/activity-tracker/app/views/users/passwords/new.html.erb new file mode 100644 index 00000000..4c403e7b --- /dev/null +++ b/week_5/activity-tracker/app/views/users/passwords/new.html.erb @@ -0,0 +1,16 @@ +

Forgot your password?

+ +<%= form_for(resource, as: resource_name, url: password_path(resource_name), html: { method: :post }) do |f| %> + <%= render "users/shared/error_messages", resource: resource %> + +
+ <%= f.label :email %>
+ <%= f.email_field :email, autofocus: true, autocomplete: "email" , class: "form-control"%>
+
+ +
+ <%= f.submit "Send me reset password instructions"%> +

+<% end %> + +<%= render "users/shared/links" %> diff --git a/week_5/activity-tracker/app/views/users/registrations/edit.html.erb b/week_5/activity-tracker/app/views/users/registrations/edit.html.erb new file mode 100644 index 00000000..038cd945 --- /dev/null +++ b/week_5/activity-tracker/app/views/users/registrations/edit.html.erb @@ -0,0 +1,43 @@ +

Edit <%= resource_name.to_s.humanize %>

+ +<%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f| %> + <%= render "users/shared/error_messages", resource: resource %> + +
+ <%= f.label :email %>
+ <%= f.email_field :email, autofocus: true, autocomplete: "email" %> +
+ + <% if devise_mapping.confirmable? && resource.pending_reconfirmation? %> +
Currently waiting confirmation for: <%= resource.unconfirmed_email %>
+ <% end %> + +
+ <%= f.label :password %> (leave blank if you don't want to change it)
+ <%= f.password_field :password, autocomplete: "new-password" %> + <% if @minimum_password_length %> +
+ <%= @minimum_password_length %> characters minimum + <% end %> +
+ +
+ <%= f.label :password_confirmation %>
+ <%= f.password_field :password_confirmation, autocomplete: "new-password" %> +
+ +
+ <%= f.label :current_password %> (we need your current password to confirm your changes)
+ <%= f.password_field :current_password, autocomplete: "current-password" %> +
+ +
+ <%= f.submit "Update" %> +
+<% end %> + +

Cancel my account

+ +

Unhappy? <%= button_to "Cancel my account", registration_path(resource_name), data: { confirm: "Are you sure?" }, method: :delete %>

+ +<%= link_to "Back", :back %> diff --git a/week_5/activity-tracker/app/views/users/registrations/new.html.erb b/week_5/activity-tracker/app/views/users/registrations/new.html.erb new file mode 100644 index 00000000..9cbd15c1 --- /dev/null +++ b/week_5/activity-tracker/app/views/users/registrations/new.html.erb @@ -0,0 +1,29 @@ +

Sign up

+ +<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %> + <%= render "users/shared/error_messages", resource: resource %> + +
+ <%= f.label :email %>
+ <%= f.email_field :email, autofocus: true, autocomplete: "email" , class: "form-control"%> +

+ +
+ <%= f.label :password %> + <% if @minimum_password_length %> + (<%= @minimum_password_length %> characters minimum) + <% end %>
+ <%= f.password_field :password, autocomplete: "new-password", class: "form-control" %> +

+ +
+ <%= f.label :password_confirmation %>
+ <%= f.password_field :password_confirmation, autocomplete: "new-password" , class: "form-control"%> +

+ +
+ <%= f.submit "Sign up" , class: "btn btn-primary"%> +

+<% end %> + +<%= render "users/shared/links" %> diff --git a/week_5/activity-tracker/app/views/users/sessions/new.html.erb b/week_5/activity-tracker/app/views/users/sessions/new.html.erb new file mode 100644 index 00000000..dc2ea083 --- /dev/null +++ b/week_5/activity-tracker/app/views/users/sessions/new.html.erb @@ -0,0 +1,28 @@ +

Log in

+ +<%= form_for(resource, as: resource_name, url: session_path(resource_name), class: "form-group col-md-6") do |f| %> +
+ <%= f.label :email %>
+ <%= f.email_field :email, autofocus: true, autocomplete: "email" , class: "form-control"%> +
+ +
+ <%= f.label :password %>
+ <%= f.password_field :password, autocomplete: "current-password", class: "form-control" %> +
+
+ + <% if devise_mapping.rememberable? %> +
+ <%= f.check_box :remember_me, class: "form-check-input"%> + <%= f.label :remember_me, class: "form-check-label" %> +
+ <% end %> +
+
+ <%= f.submit "Log in", class: "btn btn-primary" %> +
+<% end %> +
+ +<%= render "users/shared/links" %> diff --git a/week_5/activity-tracker/app/views/users/shared/_error_messages.html.erb b/week_5/activity-tracker/app/views/users/shared/_error_messages.html.erb new file mode 100644 index 00000000..ba7ab887 --- /dev/null +++ b/week_5/activity-tracker/app/views/users/shared/_error_messages.html.erb @@ -0,0 +1,15 @@ +<% if resource.errors.any? %> +
+

+ <%= I18n.t("errors.messages.not_saved", + count: resource.errors.count, + resource: resource.class.model_name.human.downcase) + %> +

+ +
+<% end %> diff --git a/week_5/activity-tracker/app/views/users/shared/_links.html.erb b/week_5/activity-tracker/app/views/users/shared/_links.html.erb new file mode 100644 index 00000000..807c7d68 --- /dev/null +++ b/week_5/activity-tracker/app/views/users/shared/_links.html.erb @@ -0,0 +1,25 @@ +<%- if controller_name != 'sessions' %> + <%= link_to "Log in", new_session_path(resource_name) , class: "btn btn-secondary" %>
+<% end %> + +<%- if devise_mapping.registerable? && controller_name != 'registrations' %> + <%= link_to "Sign up", new_registration_path(resource_name), class: "btn btn-secondary" %>

+<% end %> + +<%- if devise_mapping.recoverable? && controller_name != 'passwords' && controller_name != 'registrations' %> + <%= link_to "Forgot your password?", new_password_path(resource_name) %>
+<% end %> + +<%- if devise_mapping.confirmable? && controller_name != 'confirmations' %> + <%= link_to "Didn't receive confirmation instructions?", new_confirmation_path(resource_name) %>
+<% end %> + +<%- if devise_mapping.lockable? && resource_class.unlock_strategy_enabled?(:email) && controller_name != 'unlocks' %> + <%= link_to "Didn't receive unlock instructions?", new_unlock_path(resource_name) %>
+<% end %> + +<%- if devise_mapping.omniauthable? %> + <%- resource_class.omniauth_providers.each do |provider| %> + <%= link_to "Sign in with #{OmniAuth::Utils.camelize(provider)}", omniauth_authorize_path(resource_name, provider), method: :post %>
+ <% end %> +<% end %> diff --git a/week_5/activity-tracker/app/views/users/unlocks/new.html.erb b/week_5/activity-tracker/app/views/users/unlocks/new.html.erb new file mode 100644 index 00000000..2f4fab84 --- /dev/null +++ b/week_5/activity-tracker/app/views/users/unlocks/new.html.erb @@ -0,0 +1,16 @@ +

Resend unlock instructions

+ +<%= form_for(resource, as: resource_name, url: unlock_path(resource_name), html: { method: :post }) do |f| %> + <%= render "users/shared/error_messages", resource: resource %> + +
+ <%= f.label :email %>
+ <%= f.email_field :email, autofocus: true, autocomplete: "email" %> +
+ +
+ <%= f.submit "Resend unlock instructions" %> +
+<% end %> + +<%= render "users/shared/links" %> diff --git a/week_5/activity-tracker/authentication.md b/week_5/activity-tracker/authentication.md new file mode 100644 index 00000000..9621e41a --- /dev/null +++ b/week_5/activity-tracker/authentication.md @@ -0,0 +1,31 @@ +# Authentication | Activity Tracker + +Now that we have a good, functioning app ready, we need to secure it. Right now, anyone can access the data that we are entering. This is particularly concerning, since a lot of this might actually be sensitive information (especially in the case of a fitness tracker app), and needs to be secured properly. + +One way to do this is to allow only authorised users to be able to view the information stored. This is known as **authentication**. You provide basic information to prove that it is indeed you who are making the request, so that the application can trust you. + +In Rails, there is no in-built authentication system. However, there are great gems that are available for this very purpose. We will look at one of the most common ones, which is also in use at IRIS, called **Devise**. + +## Devise +`Devise` is an gem that provides authorisation capabilities to your Rails app, with very little difficulty. It is nearly completely customisable, and can be modified to fit all your individual needs. You can read a bit more about the project from the link in the references. + +We'll look at their README file, and quickly follow along to get it up and running. + +First, we need to get the gem. Add this to your `Gemfile` + +```ruby +gem 'devise' +``` + +Then we need to generate the files that Devise needs. This is done easily by the generater that the kind folks at Devise have made for us. + +```shell +$ rails generate devise:install +``` + +A few instructions would be printed onto your console. Make sure you follow them to properly set it up. + +Great job! Now you have Devise installed, you can set it up to protect your application. + +## References +- [Devise Repository](https://github.com/heartcombo/devise) \ No newline at end of file diff --git a/week_5/activity-tracker/bin/bundle b/week_5/activity-tracker/bin/bundle new file mode 100755 index 00000000..374a0a1f --- /dev/null +++ b/week_5/activity-tracker/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/week_5/activity-tracker/bin/importmap b/week_5/activity-tracker/bin/importmap new file mode 100755 index 00000000..36502ab1 --- /dev/null +++ b/week_5/activity-tracker/bin/importmap @@ -0,0 +1,4 @@ +#!/usr/bin/env ruby + +require_relative "../config/application" +require "importmap/commands" diff --git a/week_5/activity-tracker/bin/rails b/week_5/activity-tracker/bin/rails new file mode 100755 index 00000000..efc03774 --- /dev/null +++ b/week_5/activity-tracker/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/week_5/activity-tracker/bin/rake b/week_5/activity-tracker/bin/rake new file mode 100755 index 00000000..4fbf10b9 --- /dev/null +++ b/week_5/activity-tracker/bin/rake @@ -0,0 +1,4 @@ +#!/usr/bin/env ruby +require_relative "../config/boot" +require "rake" +Rake.application.run diff --git a/week_5/activity-tracker/bin/setup b/week_5/activity-tracker/bin/setup new file mode 100755 index 00000000..ec47b79b --- /dev/null +++ b/week_5/activity-tracker/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/week_5/activity-tracker/config.ru b/week_5/activity-tracker/config.ru new file mode 100644 index 00000000..4a3c09a6 --- /dev/null +++ b/week_5/activity-tracker/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/week_5/activity-tracker/config/application.rb b/week_5/activity-tracker/config/application.rb new file mode 100644 index 00000000..eaab4107 --- /dev/null +++ b/week_5/activity-tracker/config/application.rb @@ -0,0 +1,22 @@ +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 ActivityTracker + class Application < Rails::Application + # Initialize configuration defaults for originally generated Rails version. + config.load_defaults 7.0 + + # 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") + end +end diff --git a/week_5/activity-tracker/config/boot.rb b/week_5/activity-tracker/config/boot.rb new file mode 100644 index 00000000..988a5ddc --- /dev/null +++ b/week_5/activity-tracker/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/week_5/activity-tracker/config/cable.yml b/week_5/activity-tracker/config/cable.yml new file mode 100644 index 00000000..fc223da2 --- /dev/null +++ b/week_5/activity-tracker/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: activity_tracker_production diff --git a/week_5/activity-tracker/config/credentials.yml.enc b/week_5/activity-tracker/config/credentials.yml.enc new file mode 100644 index 00000000..4410c9ad --- /dev/null +++ b/week_5/activity-tracker/config/credentials.yml.enc @@ -0,0 +1 @@ +vy9Yyajw1b8PCBzOL90ahf4dlXAdev9jaGcu43MsIEltJ9tLudTQHZhztOYwXgig6D1/W6vai5IQKKPbfBCioSi0cdsXraMUQpVx6wPgHjU4CRMYm5gbMJ8MoGpTTRO3546ceKYioiXoAtBnnM6jyHlqdqPm/xIND5SfytLSBOJrUxg8v06TISxfhIbRlGneBeEV7I8HcrBC2ulCNToXou0oojijWGkCUYjFV/0452pmrHDX+HC4Psc252O0H7emGpqjh6puxAV6aYmiNU3cvqNjUQXxHmaH7N1jgAnR/5xB1bwZHKUB7ngTufyFzt+3ZQg5UCbuuJ+4f8lSGbrJUKNJjpVVwW5jNrRCrDm8ZMbvHCus2ApGtHu/vVjxw5bo3hWda83vQhVcBI74bNo5JnbzuKNhmQi8VEHm--ByL641PQMhBRCAI2--Mnwv25FxL4SSK6RIuW8L1Q== \ No newline at end of file diff --git a/week_5/activity-tracker/config/database.yml b/week_5/activity-tracker/config/database.yml new file mode 100644 index 00000000..fcba57f1 --- /dev/null +++ b/week_5/activity-tracker/config/database.yml @@ -0,0 +1,25 @@ +# SQLite. Versions 3.8.0 and up are supported. +# gem install sqlite3 +# +# Ensure the SQLite 3 gem is defined in your Gemfile +# gem "sqlite3" +# +default: &default + adapter: sqlite3 + pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> + timeout: 5000 + +development: + <<: *default + 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: + <<: *default + database: db/test.sqlite3 + +production: + <<: *default + database: db/production.sqlite3 diff --git a/week_5/activity-tracker/config/environment.rb b/week_5/activity-tracker/config/environment.rb new file mode 100644 index 00000000..cac53157 --- /dev/null +++ b/week_5/activity-tracker/config/environment.rb @@ -0,0 +1,5 @@ +# Load the Rails application. +require_relative "application" + +# Initialize the Rails application. +Rails.application.initialize! diff --git a/week_5/activity-tracker/config/environments/development.rb b/week_5/activity-tracker/config/environments/development.rb new file mode 100644 index 00000000..f2a3adc8 --- /dev/null +++ b/week_5/activity-tracker/config/environments/development.rb @@ -0,0 +1,72 @@ +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.action_controller.perform_caching = true + config.action_controller.enable_fragment_cache_logging = true + + 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 + + # Suppress logger output for asset requests. + config.assets.quiet = true + + config.hosts << "mittal-parth-animated-cod-gpxgvr5gwp62v4v5-3000.preview.app.github.dev" + + # 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/week_5/activity-tracker/config/environments/production.rb b/week_5/activity-tracker/config/environments/production.rb new file mode 100644 index 00000000..86a19e32 --- /dev/null +++ b/week_5/activity-tracker/config/environments/production.rb @@ -0,0 +1,93 @@ +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 + config.action_controller.perform_caching = true + + # 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? + + # Compress CSS using a preprocessor. + # config.assets.css_compressor = :sass + + # Do not fallback to assets pipeline if a precompiled asset is missed. + config.assets.compile = false + + # Enable serving of images, stylesheets, and JavaScripts from an asset server. + # config.asset_host = "http://assets.example.com" + + # Specifies the header that your server uses for sending files. + # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for Apache + # 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 = "activity_tracker_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/week_5/activity-tracker/config/environments/test.rb b/week_5/activity-tracker/config/environments/test.rb new file mode 100644 index 00000000..6ea4d1e7 --- /dev/null +++ b/week_5/activity-tracker/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/week_5/activity-tracker/config/importmap.rb b/week_5/activity-tracker/config/importmap.rb new file mode 100644 index 00000000..8dce42d4 --- /dev/null +++ b/week_5/activity-tracker/config/importmap.rb @@ -0,0 +1,7 @@ +# Pin npm packages by running ./bin/importmap + +pin "application", preload: true +pin "@hotwired/turbo-rails", to: "turbo.min.js", preload: true +pin "@hotwired/stimulus", to: "stimulus.min.js", preload: true +pin "@hotwired/stimulus-loading", to: "stimulus-loading.js", preload: true +pin_all_from "app/javascript/controllers", under: "controllers" diff --git a/week_5/activity-tracker/config/initializers/assets.rb b/week_5/activity-tracker/config/initializers/assets.rb new file mode 100644 index 00000000..8808a7f4 --- /dev/null +++ b/week_5/activity-tracker/config/initializers/assets.rb @@ -0,0 +1,12 @@ +# Be sure to restart your server when you modify this file. + +# Version of your assets, change this if you want to expire all your assets. +Rails.application.config.assets.version = "1.0" + +# Add additional assets to the asset load path. +# Rails.application.config.assets.paths << Emoji.images_path + +# Precompile additional assets. +# application.js, application.scss, and all non-JS/CSS in the app/assets +# folder are already added. +# Rails.application.config.assets.precompile += %w( admin.js admin.css ) diff --git a/week_5/activity-tracker/config/initializers/content_security_policy.rb b/week_5/activity-tracker/config/initializers/content_security_policy.rb new file mode 100644 index 00000000..54f47cf1 --- /dev/null +++ b/week_5/activity-tracker/config/initializers/content_security_policy.rb @@ -0,0 +1,25 @@ +# Be sure to restart your server when you modify this file. + +# Define an application-wide content security policy. +# See the Securing Rails Applications Guide for more information: +# https://guides.rubyonrails.org/security.html#content-security-policy-header + +# Rails.application.configure do +# config.content_security_policy do |policy| +# policy.default_src :self, :https +# policy.font_src :self, :https, :data +# policy.img_src :self, :https, :data +# policy.object_src :none +# policy.script_src :self, :https +# policy.style_src :self, :https +# # Specify URI for violation reports +# # policy.report_uri "/csp-violation-report-endpoint" +# end +# +# # Generate session nonces for permitted importmap and inline scripts +# config.content_security_policy_nonce_generator = ->(request) { request.session.id.to_s } +# config.content_security_policy_nonce_directives = %w(script-src) +# +# # Report violations without enforcing the policy. +# # config.content_security_policy_report_only = true +# end diff --git a/week_5/activity-tracker/config/initializers/devise.rb b/week_5/activity-tracker/config/initializers/devise.rb new file mode 100644 index 00000000..b875b0d2 --- /dev/null +++ b/week_5/activity-tracker/config/initializers/devise.rb @@ -0,0 +1,312 @@ +# 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 = 'e8c1b284eb9f0cd032671f2b90bb6a9ddfffc13fe47adba8fc36f6cc8a698da615d26018457b8def6d889ee10f5b35657cd63f333982421826d9c4f0306431eb' + + # ==> 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' + config.navigational_formats = ['*/*', :html, :turbo_stream] + + # 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 = '1602a35552904edd9929db1a0670e0ca6540418d144cf59d34dee4466a1958d5ad29e7efd3210919d9a363bd14aeeccc72d3443bbed795f2aa92d95dfccf2c6a' + + # 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 = true + + # 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 +end diff --git a/week_5/activity-tracker/config/initializers/filter_parameter_logging.rb b/week_5/activity-tracker/config/initializers/filter_parameter_logging.rb new file mode 100644 index 00000000..adc6568c --- /dev/null +++ b/week_5/activity-tracker/config/initializers/filter_parameter_logging.rb @@ -0,0 +1,8 @@ +# Be sure to restart your server when you modify this file. + +# Configure parameters to be filtered from the log file. Use this to limit dissemination of +# sensitive information. See the ActiveSupport::ParameterFilter documentation for supported +# notations and behaviors. +Rails.application.config.filter_parameters += [ + :passw, :secret, :token, :_key, :crypt, :salt, :certificate, :otp, :ssn +] diff --git a/week_5/activity-tracker/config/initializers/inflections.rb b/week_5/activity-tracker/config/initializers/inflections.rb new file mode 100644 index 00000000..3860f659 --- /dev/null +++ b/week_5/activity-tracker/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/week_5/activity-tracker/config/initializers/permissions_policy.rb b/week_5/activity-tracker/config/initializers/permissions_policy.rb new file mode 100644 index 00000000..00f64d71 --- /dev/null +++ b/week_5/activity-tracker/config/initializers/permissions_policy.rb @@ -0,0 +1,11 @@ +# Define an application-wide HTTP permissions policy. For further +# information see https://developers.google.com/web/updates/2018/06/feature-policy +# +# Rails.application.config.permissions_policy do |f| +# f.camera :none +# f.gyroscope :none +# f.microphone :none +# f.usb :none +# f.fullscreen :self +# f.payment :self, "https://secure.example.com" +# end diff --git a/week_5/activity-tracker/config/locales/devise.en.yml b/week_5/activity-tracker/config/locales/devise.en.yml new file mode 100644 index 00000000..260e1c4b --- /dev/null +++ b/week_5/activity-tracker/config/locales/devise.en.yml @@ -0,0 +1,65 @@ +# 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." + 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:" diff --git a/week_5/activity-tracker/config/locales/en.yml b/week_5/activity-tracker/config/locales/en.yml new file mode 100644 index 00000000..8ca56fc7 --- /dev/null +++ b/week_5/activity-tracker/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/week_5/activity-tracker/config/master.key b/week_5/activity-tracker/config/master.key new file mode 100644 index 00000000..3e69d63e --- /dev/null +++ b/week_5/activity-tracker/config/master.key @@ -0,0 +1 @@ +7ffae4e43de01027f283f3630db4227c \ No newline at end of file diff --git a/week_5/activity-tracker/config/puma.rb b/week_5/activity-tracker/config/puma.rb new file mode 100644 index 00000000..daaf0369 --- /dev/null +++ b/week_5/activity-tracker/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/week_5/activity-tracker/config/routes.rb b/week_5/activity-tracker/config/routes.rb new file mode 100644 index 00000000..9d585e44 --- /dev/null +++ b/week_5/activity-tracker/config/routes.rb @@ -0,0 +1,13 @@ +Rails.application.routes.draw do + devise_for :users + resources :activities do + collection do + get 'stats', to: 'stats#index' + end + end + root 'home#index' + # Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html + + # Defines the root path route ("/") + # root "articles#index" +end diff --git a/week_5/activity-tracker/config/storage.yml b/week_5/activity-tracker/config/storage.yml new file mode 100644 index 00000000..4942ab66 --- /dev/null +++ b/week_5/activity-tracker/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/week_5/activity-tracker/db/migrate/20230205173223_create_activities.rb b/week_5/activity-tracker/db/migrate/20230205173223_create_activities.rb new file mode 100644 index 00000000..d0fe3b06 --- /dev/null +++ b/week_5/activity-tracker/db/migrate/20230205173223_create_activities.rb @@ -0,0 +1,13 @@ +class CreateActivities < ActiveRecord::Migration[7.0] + def change + create_table :activities do |t| + t.string :title + t.string :activity_type + t.datetime :start + t.decimal :duration + t.integer :calories + + t.timestamps + end + end +end diff --git a/week_5/activity-tracker/db/migrate/20230205213322_devise_create_users.rb b/week_5/activity-tracker/db/migrate/20230205213322_devise_create_users.rb new file mode 100644 index 00000000..43927dbd --- /dev/null +++ b/week_5/activity-tracker/db/migrate/20230205213322_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/week_5/activity-tracker/db/schema.rb b/week_5/activity-tracker/db/schema.rb new file mode 100644 index 00000000..92ea8486 --- /dev/null +++ b/week_5/activity-tracker/db/schema.rb @@ -0,0 +1,36 @@ +# 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[7.0].define(version: 2023_02_05_213322) do + create_table "activities", force: :cascade do |t| + t.string "title" + t.string "activity_type" + t.datetime "start" + t.decimal "duration" + t.integer "calories" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + 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.index ["email"], name: "index_users_on_email", unique: true + t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true + end + +end diff --git a/week_5/activity-tracker/db/seeds.rb b/week_5/activity-tracker/db/seeds.rb new file mode 100644 index 00000000..bc25fce3 --- /dev/null +++ b/week_5/activity-tracker/db/seeds.rb @@ -0,0 +1,7 @@ +# This file should contain all the record creation needed to seed the database with its default values. +# The data can then be loaded with the bin/rails db:seed command (or created alongside the database with db:setup). +# +# Examples: +# +# movies = Movie.create([{ name: "Star Wars" }, { name: "Lord of the Rings" }]) +# Character.create(name: "Luke", movie: movies.first) diff --git a/week_5/activity-tracker/lib/assets/.keep b/week_5/activity-tracker/lib/assets/.keep new file mode 100644 index 00000000..e69de29b diff --git a/week_5/activity-tracker/lib/tasks/.keep b/week_5/activity-tracker/lib/tasks/.keep new file mode 100644 index 00000000..e69de29b diff --git a/week_5/activity-tracker/public/404.html b/week_5/activity-tracker/public/404.html new file mode 100644 index 00000000..2be3af26 --- /dev/null +++ b/week_5/activity-tracker/public/404.html @@ -0,0 +1,67 @@ + + + + The page you were looking for doesn't exist (404) + + + + + + +
+
+

The page you were looking for doesn't exist.

+

You may have mistyped the address or the page may have moved.

+
+

If you are the application owner check the logs for more information.

+
+ + diff --git a/week_5/activity-tracker/public/422.html b/week_5/activity-tracker/public/422.html new file mode 100644 index 00000000..c08eac0d --- /dev/null +++ b/week_5/activity-tracker/public/422.html @@ -0,0 +1,67 @@ + + + + The change you wanted was rejected (422) + + + + + + +
+
+

The change you wanted was rejected.

+

Maybe you tried to change something you didn't have access to.

+
+

If you are the application owner check the logs for more information.

+
+ + diff --git a/week_5/activity-tracker/public/500.html b/week_5/activity-tracker/public/500.html new file mode 100644 index 00000000..78a030af --- /dev/null +++ b/week_5/activity-tracker/public/500.html @@ -0,0 +1,66 @@ + + + + We're sorry, but something went wrong (500) + + + + + + +
+
+

We're sorry, but something went wrong.

+
+

If you are the application owner check the logs for more information.

+
+ + diff --git a/week_5/activity-tracker/public/apple-touch-icon-precomposed.png b/week_5/activity-tracker/public/apple-touch-icon-precomposed.png new file mode 100644 index 00000000..e69de29b diff --git a/week_5/activity-tracker/public/apple-touch-icon.png b/week_5/activity-tracker/public/apple-touch-icon.png new file mode 100644 index 00000000..e69de29b diff --git a/week_5/activity-tracker/public/favicon.ico b/week_5/activity-tracker/public/favicon.ico new file mode 100644 index 00000000..e69de29b diff --git a/week_5/activity-tracker/public/robots.txt b/week_5/activity-tracker/public/robots.txt new file mode 100644 index 00000000..c19f78ab --- /dev/null +++ b/week_5/activity-tracker/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/week_5/activity-tracker/storage/.keep b/week_5/activity-tracker/storage/.keep new file mode 100644 index 00000000..e69de29b diff --git a/week_5/activity-tracker/test/application_system_test_case.rb b/week_5/activity-tracker/test/application_system_test_case.rb new file mode 100644 index 00000000..d19212ab --- /dev/null +++ b/week_5/activity-tracker/test/application_system_test_case.rb @@ -0,0 +1,5 @@ +require "test_helper" + +class ApplicationSystemTestCase < ActionDispatch::SystemTestCase + driven_by :selenium, using: :chrome, screen_size: [1400, 1400] +end diff --git a/week_5/activity-tracker/test/channels/application_cable/connection_test.rb b/week_5/activity-tracker/test/channels/application_cable/connection_test.rb new file mode 100644 index 00000000..800405f1 --- /dev/null +++ b/week_5/activity-tracker/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/week_5/activity-tracker/test/controllers/.keep b/week_5/activity-tracker/test/controllers/.keep new file mode 100644 index 00000000..e69de29b diff --git a/week_5/activity-tracker/test/controllers/activities_controller_test.rb b/week_5/activity-tracker/test/controllers/activities_controller_test.rb new file mode 100644 index 00000000..dec4d257 --- /dev/null +++ b/week_5/activity-tracker/test/controllers/activities_controller_test.rb @@ -0,0 +1,48 @@ +require "test_helper" + +class ActivitiesControllerTest < ActionDispatch::IntegrationTest + setup do + @activity = activities(:one) + end + + test "should get index" do + get activities_url + assert_response :success + end + + test "should get new" do + get new_activity_url + assert_response :success + end + + test "should create activity" do + assert_difference("Activity.count") do + post activities_url, params: { activity: { activity_type: @activity.activity_type, calories: @activity.calories, duration: @activity.duration, start: @activity.start, title: @activity.title } } + end + + assert_redirected_to activity_url(Activity.last) + end + + test "should show activity" do + get activity_url(@activity) + assert_response :success + end + + test "should get edit" do + get edit_activity_url(@activity) + assert_response :success + end + + test "should update activity" do + patch activity_url(@activity), params: { activity: { activity_type: @activity.activity_type, calories: @activity.calories, duration: @activity.duration, start: @activity.start, title: @activity.title } } + assert_redirected_to activity_url(@activity) + end + + test "should destroy activity" do + assert_difference("Activity.count", -1) do + delete activity_url(@activity) + end + + assert_redirected_to activities_url + end +end diff --git a/week_5/activity-tracker/test/controllers/home_controller_test.rb b/week_5/activity-tracker/test/controllers/home_controller_test.rb new file mode 100644 index 00000000..eac0e336 --- /dev/null +++ b/week_5/activity-tracker/test/controllers/home_controller_test.rb @@ -0,0 +1,7 @@ +require "test_helper" + +class HomeControllerTest < ActionDispatch::IntegrationTest + # test "the truth" do + # assert true + # end +end diff --git a/week_5/activity-tracker/test/controllers/stats_controller_test.rb b/week_5/activity-tracker/test/controllers/stats_controller_test.rb new file mode 100644 index 00000000..65d8eb91 --- /dev/null +++ b/week_5/activity-tracker/test/controllers/stats_controller_test.rb @@ -0,0 +1,7 @@ +require "test_helper" + +class StatsControllerTest < ActionDispatch::IntegrationTest + # test "the truth" do + # assert true + # end +end diff --git a/week_5/activity-tracker/test/fixtures/activities.yml b/week_5/activity-tracker/test/fixtures/activities.yml new file mode 100644 index 00000000..f1684d0a --- /dev/null +++ b/week_5/activity-tracker/test/fixtures/activities.yml @@ -0,0 +1,15 @@ +# Read about fixtures at https://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html + +one: + title: MyString + activity_type: MyString + start: 2023-02-05 23:02:23 + duration: 9.99 + calories: 1 + +two: + title: MyString + activity_type: MyString + start: 2023-02-05 23:02:23 + duration: 9.99 + calories: 1 diff --git a/week_5/activity-tracker/test/fixtures/files/.keep b/week_5/activity-tracker/test/fixtures/files/.keep new file mode 100644 index 00000000..e69de29b diff --git a/week_5/activity-tracker/test/fixtures/users.yml b/week_5/activity-tracker/test/fixtures/users.yml new file mode 100644 index 00000000..d7a33292 --- /dev/null +++ b/week_5/activity-tracker/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/week_5/activity-tracker/test/helpers/.keep b/week_5/activity-tracker/test/helpers/.keep new file mode 100644 index 00000000..e69de29b diff --git a/week_5/activity-tracker/test/integration/.keep b/week_5/activity-tracker/test/integration/.keep new file mode 100644 index 00000000..e69de29b diff --git a/week_5/activity-tracker/test/mailers/.keep b/week_5/activity-tracker/test/mailers/.keep new file mode 100644 index 00000000..e69de29b diff --git a/week_5/activity-tracker/test/models/.keep b/week_5/activity-tracker/test/models/.keep new file mode 100644 index 00000000..e69de29b diff --git a/week_5/activity-tracker/test/models/activity_model_test.rb b/week_5/activity-tracker/test/models/activity_model_test.rb new file mode 100644 index 00000000..3097c757 --- /dev/null +++ b/week_5/activity-tracker/test/models/activity_model_test.rb @@ -0,0 +1,23 @@ +require "test_helper" + +class ActivityTest < ActiveSupport::TestCase + test 'has a string column title' do + assert_equal :string, Activity.type_for_attribute('title').type + end + + test 'has a string column type' do + assert_equal :string, Activity.type_for_attribute('activity_type').type + end + + test 'has a datetime column start' do + assert_equal :datetime, Activity.type_for_attribute('start').type + end + + test 'has a decimal column duration' do + assert_equal :decimal, Activity.type_for_attribute('duration').type + end + + test 'has an integer column calories' do + assert_equal :integer, Activity.type_for_attribute('calories').type + end +end \ No newline at end of file diff --git a/week_5/activity-tracker/test/models/activity_test.rb b/week_5/activity-tracker/test/models/activity_test.rb new file mode 100644 index 00000000..c07a8b91 --- /dev/null +++ b/week_5/activity-tracker/test/models/activity_test.rb @@ -0,0 +1,7 @@ +require "test_helper" + +class ActivityTest < ActiveSupport::TestCase + # test "the truth" do + # assert true + # end +end diff --git a/week_5/activity-tracker/test/models/user_test.rb b/week_5/activity-tracker/test/models/user_test.rb new file mode 100644 index 00000000..5c07f490 --- /dev/null +++ b/week_5/activity-tracker/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/week_5/activity-tracker/test/system/.keep b/week_5/activity-tracker/test/system/.keep new file mode 100644 index 00000000..e69de29b diff --git a/week_5/activity-tracker/test/system/activities_test.rb b/week_5/activity-tracker/test/system/activities_test.rb new file mode 100644 index 00000000..15feb5a2 --- /dev/null +++ b/week_5/activity-tracker/test/system/activities_test.rb @@ -0,0 +1,49 @@ +require "application_system_test_case" + +class ActivitiesTest < ApplicationSystemTestCase + setup do + @activity = activities(:one) + end + + test "visiting the index" do + visit activities_url + assert_selector "h1", text: "Activities" + end + + test "should create activity" do + visit activities_url + click_on "New activity" + + fill_in "Activity type", with: @activity.activity_type + fill_in "Calories", with: @activity.calories + fill_in "Duration", with: @activity.duration + fill_in "Start", with: @activity.start + fill_in "Title", with: @activity.title + click_on "Create Activity" + + assert_text "Activity was successfully created" + click_on "Back" + end + + test "should update Activity" do + visit activity_url(@activity) + click_on "Edit this activity", match: :first + + fill_in "Activity type", with: @activity.activity_type + fill_in "Calories", with: @activity.calories + fill_in "Duration", with: @activity.duration + fill_in "Start", with: @activity.start + fill_in "Title", with: @activity.title + click_on "Update Activity" + + assert_text "Activity was successfully updated" + click_on "Back" + end + + test "should destroy Activity" do + visit activity_url(@activity) + click_on "Destroy this activity", match: :first + + assert_text "Activity was successfully destroyed" + end +end diff --git a/week_5/activity-tracker/test/test_helper.rb b/week_5/activity-tracker/test/test_helper.rb new file mode 100644 index 00000000..d713e377 --- /dev/null +++ b/week_5/activity-tracker/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/week_5/activity-tracker/vendor/.keep b/week_5/activity-tracker/vendor/.keep new file mode 100644 index 00000000..e69de29b diff --git a/week_5/activity-tracker/vendor/javascript/.keep b/week_5/activity-tracker/vendor/javascript/.keep new file mode 100644 index 00000000..e69de29b