Skip to content

Commit

Permalink
added login and logout method, along with rspec tests
Browse files Browse the repository at this point in the history
  • Loading branch information
joehannis committed Jun 3, 2023
1 parent 21e46d7 commit 93521b8
Show file tree
Hide file tree
Showing 8 changed files with 143 additions and 28 deletions.
48 changes: 43 additions & 5 deletions app.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
establish_database_connection

class Application < Sinatra::Base
enable :sessions
configure :development do
register Sinatra::Reloader
also_reload 'lib/database_connection'
Expand All @@ -26,21 +27,58 @@ class Application < Sinatra::Base
erb(:index)
end

post '/' do
post '/account_page' do
current_time = Time.now + 1 * 60 * 60 # Get the current time with GMT offset
Post.create(time: current_time, message: params[:message], user_id: 1)
Post.create_post(current_time, params[:message], session[:user_id])

# Append the new post to the class variable
@@posts.unshift("#{current_time} #{User.find(1).name} #{User.find(1).username} #{params[:message]}")
@@posts.unshift("#{current_time} #{User.find(session[:user_id]).name} #{User.find(session[:user_id]).username} #{params[:message]}")


redirect '/'
redirect '/account_page'
end


get '/signup' do
erb(:signup)
end

get '/login' do
erb(:login)
end

get '/logout' do
session.clear
redirect '/'
end

get '/login_failure' do
erb(:login_failure)
end

post '/login' do
user = User.sign_in(params[:username], params[:password])
if user
session[:user_id] = user.id
redirect '/account_page'
else
redirect '/login_failure'
end
end



get '/account_page' do
if session[:user_id].nil?
# No user id in the session
# so the user is not logged in.
redirect '/login'
else
# The user is logged in, display their account page.
erb(:account)
end
end


post '/signup' do
database = User.all_records
match_found = false
Expand Down
13 changes: 10 additions & 3 deletions lib/user.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,14 @@ def self.create_user(name, username, email, password)
user
end

def authenticate(password)
BCrypt::Password.new(self.password) == password
def self.sign_in(username, password)
user = User.find_by(username: username)
return nil unless user

stored_password = BCrypt::Password.new(user.password)
return nil unless stored_password == password

user
end
end
end

37 changes: 32 additions & 5 deletions spec/integration/application.spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -39,14 +39,20 @@
expect(response.body).to include('Success')
end
end
context 'Post /' do
context 'Post /account_page' do
it 'adds peep to chitter' do
response = post('/', message: 'Need to start working', user_id: 2)
Post.create_post(Time.now, 'Need to start working', 2)

expect(response.status).to eq(302)
post '/login', username: 'test_user', password: 'password' # Login the user and set the session

post '/account_page', { message: 'Need to start working' }, 'rack.session' => { user_id: 2 }

follow_redirect! # Follow the redirect to the new page
expect(last_request.path).to eq('/account_page') # Ensure we are on the expected page
expect(last_response.body).to include('Need to start working') # Check the content of the page

expect(last_response.status).to eq(200) # Optionally check the status code
end
end

context 'Post /signup' do
it 'recognises that a username already exists, redirects to the signup page' do
user = User.new
Expand All @@ -57,5 +63,26 @@
expect(response.headers['Location']).to include('/signup')
end
end
context 'Post /login' do
it 'logs into user account' do
response = post('/login', { username: 'laurenhannis', password: 'passwordlauren' })
User.sign_in('laurenhannis', 'passwordlauren')

expect(response.status).to eq(302) # Assuming it redirects
expect(response.headers['Location']).to include('/account_page')
end
end
context 'GET /logout'
it 'clears the session and redirects to the home page' do
post '/login', { username: 'testuser', password: 'password' }

get '/logout'

expect(last_response.redirect?).to be true
follow_redirect!

expect(last_request.path).to eq('/')
expect(rack_mock_session.cookie_jar['rack.session']).not_to include('user_id')
end
end

29 changes: 21 additions & 8 deletions spec/seeds/user_seeds.sql
Original file line number Diff line number Diff line change
@@ -1,18 +1,31 @@
DROP TABLE IF EXISTS users CASCADE;

-- Table Definition
CREATE TABLE users (
SET client_min_messages = WARNING;
CREATE EXTENSION IF NOT EXISTS pgcrypto;
-- Define the table structure
CREATE TABLE IF NOT EXISTS users (
id SERIAL PRIMARY KEY,
name text,
username text,
email text,
password text
);

-- Clear existing data and reset the auto-incrementing ID
TRUNCATE TABLE users RESTART IDENTITY;

-- Helper function to encrypt passwords using BCrypt
CREATE OR REPLACE FUNCTION encrypt_password(password text)
RETURNS text AS $$
DECLARE
hashed_password text;
BEGIN
hashed_password := crypt(password, gen_salt('bf'));
RETURN hashed_password;
END;
$$ LANGUAGE plpgsql;

-- Insert user records with encrypted passwords
INSERT INTO users ("name", "username", "email", "password") VALUES
('Joe Hannis', 'joehannis', '[email protected]', 'passwordjoe'),
('Jake Hannis', 'jakehannis', '[email protected]', 'passwordjake'),
('Lauren Hannis', 'laurenhannis', '[email protected]', 'passwordlauren'),
('Luna Hannis', 'lunahannis', '[email protected]', 'passwordluna');
('Joe Hannis', 'joehannis', '[email protected]', encrypt_password('passwordjoe')),
('Jake Hannis', 'jakehannis', '[email protected]', encrypt_password('passwordjake')),
('Lauren Hannis', 'laurenhannis', '[email protected]', encrypt_password('passwordlauren')),
('Luna Hannis', 'lunahannis', '[email protected]', encrypt_password('passwordluna'));
15 changes: 15 additions & 0 deletions views/account.erb
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<html>
<head></head>
<body>
<h1>Chitter</h1>
<div>What would you like to say?</div>
<div><form action="/account_page" method="POST">
<input type="text" name="message">
<input type="submit" value="Post a message!">
</form></div>
<% @@posts.each do |post| %>
<%= post %><br />
<% end %>
<a href="http://localhost:9292/logout">Logout</a>
</body>
</html>
9 changes: 2 additions & 7 deletions views/index.erb
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,9 @@
<head></head>
<body>
<h1>Chitter</h1>
<div>Signup Here: <a href="http://localhost:9292/signup">Signup</a></div>
<div>What would you like to say?</div>
<div><form action="/" method="POST">
<input type="text" name="message">
<input type="submit" value="Post a message!">
</form></div>
<div>Signup Here: <a href="http://localhost:9292/signup">Signup</a><br />Login here: <a href="http://localhost:9292/login">Login</a></div>
<% @@posts.each do |post| %>
<%= post %><br />
<% end %>
</body>
</html>
</html>
13 changes: 13 additions & 0 deletions views/login.erb
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<html>
<head></head>
<body>
<h1>Welcome to Chitter!</h1>
<div>Please log in below</div>
<div><form action="/login" method="POST">
<div>Username</div>
<input type="text" name="username">
<div>Password</div>
<input type="password" name="password">
<input type="submit" value="Login">
</body>
</html>
7 changes: 7 additions & 0 deletions views/login_failure.erb
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<html>
<head></head>
<body>
<h1>Login failure</h1>
<div><a href="http://localhost:9292/login">click here to try again</a></div>
</body>
</html>

0 comments on commit 93521b8

Please sign in to comment.