diff --git a/.eslintrc.js b/.eslintrc.js new file mode 100644 index 0000000000..123a7ad668 --- /dev/null +++ b/.eslintrc.js @@ -0,0 +1,12 @@ +module.exports = { + "env": { + "browser": true, + "commonjs": true, + "es2021": true + }, + "parserOptions": { + "ecmaVersion": "latest" + }, + "rules": { + } +} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000..4c8e916983 --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +node_modules +.env +.DS_Store +package-lock.json + +cypress/screenshots +cypress/videos diff --git a/.rubocop.yml b/.rubocop.yml deleted file mode 100644 index a1c9ba45e2..0000000000 --- a/.rubocop.yml +++ /dev/null @@ -1,42 +0,0 @@ - -# _____ ____ ____ __ _ __ -# / ___/ _____ ____ _ / __// __/____ / / (_)____ / /_ -# \__ \ / ___// __ `// /_ / /_ / __ \ / / / // __ \ / __/ -# ___/ // /__ / /_/ // __// __// /_/ // /___ / // / / // /_ -# /____/ \___/ \__,_//_/ /_/ 1 \____//_____//_//_/ /_/ \__/ -# -# The linter file that doesn't lead junior developers to bad habits. -# https://github.com/makersacademy/scaffolint -# -# Configure Rubocop to use the config file in the Scaffolint GitHub repo -inherit_from: - - https://raw.githubusercontent.com/makersacademy/scaffolint/v2.2.0/.rubocop.yml - -# Rails -# ===== -# -# Here are some additions to Scaffolint for Rails apps. -# -# Enable the Rails rules included in the rubocop-rails gem. -require: - - rubocop-rails - -# Exclusions -# ========== -# -# Rails has powerful generators. -# -# Some auto-generated files are edited frequently. We want to lint them, -# so let's avoid adding them to this list. -# e.g. controllers, models, views -# -# Other auto-generated files are usually not edited afterwards. -# There's almost zero value in linting them, so let's exclude them. -# e.g. binstubs, config, migrations - -AllCops: - Exclude: - - 'bin/*' - - 'config/**/*' - - 'db/**/*' - - 'vendor/**/*' diff --git a/README.md b/README.md index 6806f8db2a..b93dabffe0 100644 --- a/README.md +++ b/README.md @@ -1,41 +1,75 @@ Instagram Challenge =================== -## Instructions +This app is a copy of instagram written in Javascript. Express was used to create the server and routes, Mongodb is the database where the data is stored and mongoose was used to connect the two together. -* Feel free to use Google, your notes, books, etc., but work on your own -* If you refer to the solution of another coach or student, please put a link to that in your README -* If you have a partial solution, **still check in a partial solution** -* You must submit a pull request to this repo with your code by 9am Monday morning +All the necessary files for this app have been separated into appropriate folders. The [views](https://github.com/jmcnally17/instagram-challenge/tree/main/views) folder contains the HBS files that contain the HTML code for each page. The [routes](https://github.com/jmcnally17/instagram-challenge/tree/main/routes) folder contains the defined routes for each group of objects that govern HTTP requests throughout the app, with help from the [controllers](https://github.com/jmcnally17/instagram-challenge/tree/main/controllers) folder. Finally, the object classes are defined in the [models](https://github.com/jmcnally17/instagram-challenge/tree/main/models) folder, which use Mongoose to create the necessary Schema which define the classes themselves. These Schema also determine what information gets stored in the database. -## Task +So far, the functionality is limited due to not having a lot of time to work on this project. -Build Instagram: Simple huh! +## Getting Started -Your challenge is to build Instagram using Rails. You'll need **users** who can post **pictures**, write **comments** on pictures and **like** a picture. Style it like Instagram's website (or more awesome). +If you haven't already, install nvm using homebrew: -Bonus if you can add filters! +``` +brew install nvm +``` -## How to start +Then, open a new terminal and install Node.js: -1. Produce some stories, break them down into tasks, and estimate -2. Fork this repo, clone, etc -3. Initialize a new rails project +``` +nvm install node +``` -Remember to proceed in small steps! Getting confused? Make the steps even smaller. +Now you can clone this repository and install the necessary dependencies: -## Code Quality +``` +git clone https://github.com/jmcnally17/instagram-challenge +npm install +``` -For linting, you can use the `.rubocop.yml` in this repository (or your own!). -You'll need these gems: +Mongodb needs to be installed and started as well: -```ruby -group :development, :test do - gem 'rubocop', '1.20', require: false - gem 'rubocop-rails' -end ``` +brew tap mongodb/brew +brew install mongodb-community@5.0 +brew services start mongodb-community@5.0 +``` + +## How To Use + +To start using the app, start by running the server using: + +``` +npm start +``` + +Then, in your browser, enter `localhost:3000` in the address bar to visit the site. There, you can sign up, log in, log out and post image URLs that will be rendered on the posts page, which you can only visit when you are signed in. + +## Testing + +Jest was used for unit tests which applied to the models, while Cypress carried out integration tests to mimic user input in order to see the correct results were displayed on the pages. To run the unit tests, simply enter `jest` or `npm run test:unit` into the terminal. In order to run the integration tests, first the test server needs to be run by entering: + +``` +npm run start:test +``` + +Then the integration tests can be initiated by entering: + +``` +npm run test:integration +``` + +All tests can be ran together at once by simply entering `npm test` into the terminal *(remember the integration tests will need the test server to be runnning in order for them to pass)*. + +## Improvements + +Had I had more time, I would have liked to implement the following functionality: -You can also lint Javascript, CSS, and ERB — feel free to research this. These -will help you to train yourself to produce cleaner code — and will often alert -you to mistakes or mishaps! +1. Users are automatically logged in after registering. +2. Users cannot sign up with existing emails and passwords would be encrypted +3. Posts would be linked with the user who posted it via a foreign key. +4. Image files could be uploaded to the site instead of having to enter the URL for an existing photo on the internet. +5. Photos can be liked and commented on. +6. Posts can be deleted. +7. Bonus: add filters to posts. diff --git a/app.js b/app.js new file mode 100644 index 0000000000..9b84fa86e4 --- /dev/null +++ b/app.js @@ -0,0 +1,76 @@ +const createError = require('http-errors'); +const express = require('express'); +const path = require('path'); +const cookieParser = require('cookie-parser'); +const logger = require('morgan'); +const session = require("express-session"); +const methodOverride = require("method-override"); + + +const homeRouter = require('./routes/home'); +const postsRouter = require('./routes/posts'); +const sessionsRouter = require('./routes/sessions'); +const usersRouter = require('./routes/users'); + +const app = express(); + +// view engine setup +app.set('views', path.join(__dirname, 'views')); +app.set('view engine', 'hbs'); + +app.use(logger('dev')); +app.use(express.json()); +app.use(express.urlencoded({ extended: true })); +app.use(cookieParser()); +app.use(express.static(path.join(__dirname, 'public'))); +app.use(methodOverride("_method")); + +app.use( + session({ + key: "user_sid", + secret: "super_secret", + resave: false, + saveUninitialized: false, + cookie: { + expires: 600000, + }, + }) +); + +app.use((req, res, next) => { + if (req.cookies.user_sid && !req.session.user) { + res.clearCookie("user_sid"); + } + next(); +}); + +const sessionChecker = (req, res, next) => { + if (!req.session.user && !req.cookies.user_sid) { + res.redirect('/'); + } else { + next(); + } +}; + +app.use('/', homeRouter); +app.use('/posts', sessionChecker, postsRouter); +app.use('/sessions', sessionsRouter); +app.use('/users', usersRouter); + +// catch 404 and forward to error handler +app.use(function(req, res, next) { + next(createError(404)); +}); + +// error handler +app.use(function(err, req, res, next) { + // set locals, only providing error in development + res.locals.message = err.message; + res.locals.error = req.app.get('env') === 'development' ? err : {}; + + // render the error page + res.status(err.status || 500); + res.render('error'); +}); + +module.exports = app; diff --git a/bin/www b/bin/www new file mode 100755 index 0000000000..eff3f89c69 --- /dev/null +++ b/bin/www @@ -0,0 +1,101 @@ +#!/usr/bin/env node + +/** + * Module dependencies. + */ + +var app = require('../app'); +var debug = require('debug')('instagram-challenge:server'); +var http = require('http'); +const mongoose = require('mongoose'); + +/** + * Get port from environment and store in Express. + */ + +var port = normalizePort(process.env.PORT || '3000'); +app.set('port', port); + +/** + * Connect to mongodb + */ + +var mongoDbUrl = process.env.MONGODB_URI || "mongodb://127.0.0.1/fakesta"; +mongoose.connect(mongoDbUrl, { + useNewUrlParser: true, + useUnifiedTopology: true, +}); + +var db = mongoose.connection; +db.on("error", console.error.bind(console, "MongoDB connection error:")); + +/** + * Create HTTP server. + */ + +var server = http.createServer(app); + +/** + * Listen on provided port, on all network interfaces. + */ + +server.listen(port); +server.on('error', onError); +server.on('listening', onListening); + +/** + * Normalize a port into a number, string, or false. + */ + +function normalizePort(val) { + var port = parseInt(val, 10); + + if (isNaN(port)) { + // named pipe + return val; + } + + if (port >= 0) { + // port number + return port; + } + + return false; +} + +/** + * Event listener for HTTP server "error" event. + */ + +function onError(error) { + if (error.syscall !== 'listen') { + throw error; + } + + var bind = typeof port === "string" ? "Pipe " + port : "Port " + port; + + // handle specific listen errors with friendly messages + switch (error.code) { + case 'EACCES': + console.error(bind + ' requires elevated privileges'); + process.exit(1); + break; + case 'EADDRINUSE': + console.error(bind + ' is already in use'); + process.exit(1); + break; + default: + throw error; + } +} + +/** + * Event listener for HTTP server "listening" event. + */ + +function onListening() { + var addr = server.address(); + var bind = typeof addr === "string" ? "pipe " + addr : "port " + addr.port; + console.log("Now listening on " + bind); + debug('Listening on ' + bind); +} diff --git a/controllers/home.js b/controllers/home.js new file mode 100644 index 0000000000..37fc7bfc49 --- /dev/null +++ b/controllers/home.js @@ -0,0 +1,7 @@ +const HomeController = { + Index: (req, res) => { + res.render('home/index', { title: 'Fakestagram' }); + }, +}; + +module.exports = HomeController; \ No newline at end of file diff --git a/controllers/posts.js b/controllers/posts.js new file mode 100644 index 0000000000..57b400e8e6 --- /dev/null +++ b/controllers/posts.js @@ -0,0 +1,24 @@ +const Post = require('../models/post'); + +const PostsController = { + Index: (req, res) => { + Post.find((err, posts) => { + if (err) { + throw err; + } + res.render("posts/index", {posts: posts}); + }); + }, + + Create: (req, res) => { + const post = new Post(req.body); + post.save((err) => { + if (err) { + throw err; + } + res.status(200).redirect('/posts'); + }); + }, +}; + +module.exports = PostsController; \ No newline at end of file diff --git a/controllers/sessions.js b/controllers/sessions.js new file mode 100644 index 0000000000..a4db0da489 --- /dev/null +++ b/controllers/sessions.js @@ -0,0 +1,26 @@ +const User = require("../models/user"); + +const SessionsController = { + Create: (req, res) => { + const email = req.body.email; + const password = req.body.password; + + User.findOne({ email: email }).then((user) => { + if (!user || user.password != password) { + res.redirect("/"); + } else { + req.session.user = user; + res.redirect("/posts"); + } + }); + }, + + Destroy: (req, res) => { + if (req.session.user && req.cookies.user_sid) { + res.clearCookie("user_sid"); + } + res.redirect("/"); + }, +}; + +module.exports = SessionsController; \ No newline at end of file diff --git a/controllers/users.js b/controllers/users.js new file mode 100644 index 0000000000..1bce21c539 --- /dev/null +++ b/controllers/users.js @@ -0,0 +1,19 @@ +const User = require('../models/user'); + +const UsersController = { + New: (req, res) => { + res.render("users/new", {}); + }, + + Create: (req, res) => { + const user = new User(req.body); + user.save((err) => { + if (err) { + throw err; + } + res.status(201).redirect('/') + }); + }, +}; + +module.exports = UsersController; \ No newline at end of file diff --git a/cypress.json b/cypress.json new file mode 100644 index 0000000000..f5d39ff425 --- /dev/null +++ b/cypress.json @@ -0,0 +1,3 @@ +{ + "baseUrl": "http://localhost:3030" +} \ No newline at end of file diff --git a/cypress/integration/homepage_spec.js b/cypress/integration/homepage_spec.js new file mode 100644 index 0000000000..38f0d52462 --- /dev/null +++ b/cypress/integration/homepage_spec.js @@ -0,0 +1,13 @@ +describe("Homepage", () => { + it("has a title and welcome message", () => { + cy.visit("/"); + cy.get(".title").should("contain", "Fakestagram"); + cy.contains("Welcome to Fakestagram"); + }); + + it("has a link to the sign up page", () => { + cy.visit("/"); + cy.get('.link').click(); + cy.url().should("contain", "/users/new"); + }); +}); \ No newline at end of file diff --git a/cypress/integration/user_can_sign_in_spec.js b/cypress/integration/user_can_sign_in_spec.js new file mode 100644 index 0000000000..4e3c62c59a --- /dev/null +++ b/cypress/integration/user_can_sign_in_spec.js @@ -0,0 +1,17 @@ +describe("Sign in", () => { + it("sends the user to the posts page when signing in", () => { + cy.visit("/users/new"); + cy.get("#username").type("person2"); + cy.get("#email").type("person2@email.co.uk"); + cy.get("#password").type("password"); + cy.get("#submit").click(); + + cy.url().should("eq", "http://localhost:3030/") + + cy.get("#email").type("person2@email.co.uk"); + cy.get("#password").type("password"); + cy.get("#submit").click(); + + cy.url().should("contain", "/posts"); + }); +}); \ No newline at end of file diff --git a/cypress/integration/user_can_sign_up_spec.js b/cypress/integration/user_can_sign_up_spec.js new file mode 100644 index 0000000000..55bab42225 --- /dev/null +++ b/cypress/integration/user_can_sign_up_spec.js @@ -0,0 +1,11 @@ +describe("Sign up", () => { + it("allows users to sign up with their details", () => { + cy.visit("/users/new"); + cy.get("#username").type("person1"); + cy.get("#email").type("person1@email.co.uk"); + cy.get("#password").type("password"); + cy.get("#submit").click(); + + cy.url().should("eq", "http://localhost:3030/") + }); +}); \ No newline at end of file diff --git a/cypress/plugins/index.js b/cypress/plugins/index.js new file mode 100644 index 0000000000..59b2bab6e4 --- /dev/null +++ b/cypress/plugins/index.js @@ -0,0 +1,22 @@ +/// +// *********************************************************** +// This example plugins/index.js can be used to load plugins +// +// You can change the location of this file or turn off loading +// the plugins file with the 'pluginsFile' configuration option. +// +// You can read more here: +// https://on.cypress.io/plugins-guide +// *********************************************************** + +// This function is called when a project is opened or re-opened (e.g. due to +// the project's config changing) + +/** + * @type {Cypress.PluginConfig} + */ +// eslint-disable-next-line no-unused-vars +module.exports = (on, config) => { + // `on` is used to hook into various events Cypress emits + // `config` is the resolved Cypress config +} diff --git a/cypress/support/commands.js b/cypress/support/commands.js new file mode 100644 index 0000000000..119ab03f7c --- /dev/null +++ b/cypress/support/commands.js @@ -0,0 +1,25 @@ +// *********************************************** +// This example commands.js shows you how to +// create various custom commands and overwrite +// existing commands. +// +// For more comprehensive examples of custom +// commands please read more here: +// https://on.cypress.io/custom-commands +// *********************************************** +// +// +// -- This is a parent command -- +// Cypress.Commands.add('login', (email, password) => { ... }) +// +// +// -- This is a child command -- +// Cypress.Commands.add('drag', { prevSubject: 'element'}, (subject, options) => { ... }) +// +// +// -- This is a dual command -- +// Cypress.Commands.add('dismiss', { prevSubject: 'optional'}, (subject, options) => { ... }) +// +// +// -- This will overwrite an existing command -- +// Cypress.Commands.overwrite('visit', (originalFn, url, options) => { ... }) diff --git a/cypress/support/index.js b/cypress/support/index.js new file mode 100644 index 0000000000..e353acef0f --- /dev/null +++ b/cypress/support/index.js @@ -0,0 +1,20 @@ +// *********************************************************** +// This example support/index.js is processed and +// loaded automatically before your test files. +// +// This is a great place to put global configuration and +// behavior that modifies Cypress. +// +// You can change the location of this file or turn off +// automatically serving support files with the +// 'supportFile' configuration option. +// +// You can read more here: +// https://on.cypress.io/configuration +// *********************************************************** + +// Import commands.js using ES2015 syntax: +require('./commands'); + +// Alternatively you can use CommonJS syntax: +// require('./commands') diff --git a/models/post.js b/models/post.js new file mode 100644 index 0000000000..fe25c17a28 --- /dev/null +++ b/models/post.js @@ -0,0 +1,10 @@ +const mongoose = require('mongoose'); + +const PostSchema = new mongoose.Schema({ + url: String, + caption: String, +}); + +const Post = mongoose.model("Post", PostSchema); + +module.exports = Post; \ No newline at end of file diff --git a/models/user.js b/models/user.js new file mode 100644 index 0000000000..9e1cd57271 --- /dev/null +++ b/models/user.js @@ -0,0 +1,11 @@ +const mongoose = require('mongoose'); + +const UserSchema = new mongoose.Schema({ + username: String, + email: String, + password: String, +}); + +const User = mongoose.model("User", UserSchema); + +module.exports = User \ No newline at end of file diff --git a/package.json b/package.json new file mode 100644 index 0000000000..5d7814a2d1 --- /dev/null +++ b/package.json @@ -0,0 +1,31 @@ +{ + "name": "instagram-challenge", + "version": "0.0.0", + "private": true, + "scripts": { + "start": "node ./bin/www", + "start:test": "PORT=3030 MONGODB_URI='mongodb://127.0.0.1/fakesta_test' npm start", + "test": "npm run lint && npm run test:unit && npm run test:integration", + "lint": "eslint .", + "test:unit": "jest", + "test:integration": "cypress run" + }, + "dependencies": { + "cookie-parser": "~1.4.4", + "debug": "~2.6.9", + "express": "~4.16.1", + "express-session": "^1.17.3", + "hbs": "^4.2.0", + "http-errors": "~1.6.3", + "jade": "^0.29.0", + "method-override": "^3.0.0", + "mongodb": "^4.6.0", + "mongoose": "^6.3.3", + "morgan": "~1.9.1", + "nodemon": "^2.0.16" + }, + "devDependencies": { + "cypress": "^9.6.1", + "eslint": "^8.15.0" + } +} diff --git a/public/stylesheets/style.css b/public/stylesheets/style.css new file mode 100644 index 0000000000..bfb9338af4 --- /dev/null +++ b/public/stylesheets/style.css @@ -0,0 +1,4 @@ +body { + padding: 50px; + font: 14px "Lucida Grande", Helvetica, Arial, sans-serif; +} diff --git a/routes/home.js b/routes/home.js new file mode 100644 index 0000000000..a84695f002 --- /dev/null +++ b/routes/home.js @@ -0,0 +1,9 @@ +var express = require('express'); +var router = express.Router(); + +const HomeController = require('../controllers/home'); + +/* GET home page. */ +router.get('/', HomeController.Index); + +module.exports = router; diff --git a/routes/posts.js b/routes/posts.js new file mode 100644 index 0000000000..49d37021bb --- /dev/null +++ b/routes/posts.js @@ -0,0 +1,9 @@ +var express = require("express"); +var router = express.Router(); + +const PostsController = require("../controllers/posts"); + +router.get('/', PostsController.Index); +router.post('/', PostsController.Create); + +module.exports = router \ No newline at end of file diff --git a/routes/sessions.js b/routes/sessions.js new file mode 100644 index 0000000000..357f0594fe --- /dev/null +++ b/routes/sessions.js @@ -0,0 +1,9 @@ +var express = require("express"); +var router = express.Router(); + +const SessionsController = require("../controllers/sessions"); + +router.post("/", SessionsController.Create); +router.delete("/", SessionsController.Destroy); + +module.exports = router; \ No newline at end of file diff --git a/routes/users.js b/routes/users.js new file mode 100644 index 0000000000..793ce87755 --- /dev/null +++ b/routes/users.js @@ -0,0 +1,9 @@ +var express = require("express"); +var router = express.Router(); + +const UsersController = require ("../controllers/users"); + +router.get("/new", UsersController.New); +router.post("/", UsersController.Create); + +module.exports = router; diff --git a/spec/models/user.spec.js b/spec/models/user.spec.js new file mode 100644 index 0000000000..70cf79fdc0 --- /dev/null +++ b/spec/models/user.spec.js @@ -0,0 +1,24 @@ +const mongoose = require("mongoose"); + +require("../mongodb_helper"); +const User = require('../../models/user'); + +describe("User", () => { + beforeEach((done) => { + mongoose.connection.collections.users.drop(() => { + done(); + }); + }); + + it("has a username, email and password", () => { + const user = new User({ + username: "user1", + email: "user1@email.co.uk", + password: "password" + }); + + expect(user.username).toEqual("user1"); + expect(user.email).toEqual("user1@email.co.uk"); + expect(user.password).toEqual("password"); + }); +}); \ No newline at end of file diff --git a/spec/mongodb_helper.js b/spec/mongodb_helper.js new file mode 100644 index 0000000000..8a61514494 --- /dev/null +++ b/spec/mongodb_helper.js @@ -0,0 +1,20 @@ +var mongoose = require('mongoose'); + +beforeAll(function (done) { + mongoose.connect('mongodb://127.0.0.1/fakesta_test', { + useNewUrlParser: true, + useUnifiedTopology: true, + }); + + var db = mongoose.connection; + db.on("error", console.error.bind(console, "MongoDB connection error:")); + db.on("open", function () { + done(); + }); +}); + +afterAll(function (done) { + mongoose.connection.close(true, function () { + done(); + }); +}); \ No newline at end of file diff --git a/views/error.hbs b/views/error.hbs new file mode 100644 index 0000000000..e69de29bb2 diff --git a/views/home/index.hbs b/views/home/index.hbs new file mode 100644 index 0000000000..8791efad09 --- /dev/null +++ b/views/home/index.hbs @@ -0,0 +1,10 @@ +

{{title}}

+Welcome to {{title}}! +

+
+ + + +
+

+Don't have account yet? Sign up \ No newline at end of file diff --git a/views/layout.hbs b/views/layout.hbs new file mode 100644 index 0000000000..e1e2fcf05a --- /dev/null +++ b/views/layout.hbs @@ -0,0 +1,10 @@ + + + + {{title}} + + + + {{{body}}} + + \ No newline at end of file diff --git a/views/posts/index.hbs b/views/posts/index.hbs new file mode 100644 index 0000000000..4073dd5ed0 --- /dev/null +++ b/views/posts/index.hbs @@ -0,0 +1,21 @@ +

Posts

+ +
+ + + +
+ +
+ +{{#each posts}} +
+ +
{{this.caption}}
+
+
+{{/each}} + +
+ +
\ No newline at end of file diff --git a/views/users/new.hbs b/views/users/new.hbs new file mode 100644 index 0000000000..bd7c8abacf --- /dev/null +++ b/views/users/new.hbs @@ -0,0 +1,8 @@ +

Sign up

+ +
+ + + + +
\ No newline at end of file