Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .env
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
PORT=5000
GITHUB_CLIENT_SECRET=c301c36006269a5b6430199907d3e3c8aad06a6c
GITHUB_CLIENT_ID=bb9ec6bae003b51b42f3
GITHUB_REDIRECT_URI=https://a3-dinmukhamed-umbetzhan.herokuapp.com/auth/success
MONGO_URI=mongodb+srv://admin:[email protected]/?retryWrites=true&w=majority
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.idea
node_modules
/node_modules
125 changes: 23 additions & 102 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,116 +1,37 @@
Assignment 3 - Persistence: Two-tier Web Application with Database, Express server, and CSS template
===

Due: September 22nd, by 11:59 AM.
## Notify

This assignnment continues where we left off, extending it to use the most popular Node.js server framework (express),
a database (mongodb), and a CSS application framework / template of your choice (Boostrap, Material Design, Semantic UI, Pure etc.)
https://a3-dinmukhamed-umbetzhan.herokuapp.com/auth/login

Baseline Requirements
---
For this project I used heroku to achieve 5 points.

Your application is required to implement the following functionalities:
The goal of Notify is to add/delete and edit notes that was created by user. Any user can log in using github account, their nickname will be stored in the DB of the application. Each session is also stored in the DB of the application. After logging in user can use functionality mentioned above.

- a `Server`, created using Express (no alternatives will be accepted for this assignment)
- a `Results` functionality which shows all data associated with a logged in user (except passwords)
- a `Form/Entry` functionality which allows users to add, modify, and delete data items (must be all three!) associated with their user name / account.
- Use of at least five [Express middleware packages](https://expressjs.com/en/resources/middleware.html). Explore! One of these five middleware
can be a custom function that you write yourself; if you choose to do this, make sure to describe what this function is in your README.
- Persistent data storage in between server sessions using [mongodb](https://www.mongodb.com/cloud/atlas)
- Use of a [CSS framework or template](https://github.com/troxler/awesome-css-frameworks).
This should do the bulk of your styling/CSS for you and be appropriate to your application.
For example, don't use [NES.css](https://nostalgic-css.github.io/NES.css/) (which is awesome!) unless you're creating a game or some type of retro 80s site.
Biggest challenge while creating this application was storing the session of each user in the DB, since the documentation of the middleware is out of date and I had to find out the resolution on the web.

Your application is required to demonstrate the use of the following concepts:
For this project I have chosen authorization via github to achieve points and face the hardest challenge. And to be honest it was easy to implement since I have done it earlier.

HTML:
- HTML input tags and form fields of various flavors (`<textarea>`, `<input>`, checkboxes, radio buttons etc.)
- HTML that can display all data *for a particular authenticated user*. Note that this is different from the last assignnment, which required the display of all data in memory on the server.
Middleware packages I used:
- CORS middleware - Cross-Origin Resource Sharing. Done to bypass the access-control-allow-origin headers
- cookie-parser - used it to store cookies on the web application
- ejs - used as a view engine
- mongoose - used to connect to MongoDB
- dotenv - used to create environment variables

Note that it might make sense to have two pages for this assignment, one that handles login / authentication, and one that contains the rest of your application.
For example, when visiting the home page for the assignment, users could be presented with a login form. After submitting the login form, if the login is
successful, they are taken to the main application. If they fail, they are sent back to the login to try again. For this assignment, it is acceptable to simply create
new user accounts upon login if none exist, however, you must alert your users to this fact.

CSS:
- CSS styling should primarily be provided by your chosen template/framework.
Oftentimes a great deal of care has been put into designing CSS templates;
don't override their stylesheets unless you are extremely confident in your graphic design capabilities.
The idea is to use CSS templates that give you a professional looking design aesthetic without requiring you to be a graphic designer yourself.

JavaScript:
- At minimum, a small amount of front-end JavaScript to get / fetch data from the server.
See the [previous assignment](https://github.com/cs4241-19a/a2-shortstack) for reference.

Node.js:
- A server using Express, at least five pieces of Express middleware, and a persistent database (mongodb).

General:
- Your site should achieve at least 90% on the `Performance`, `Best Practices`, `Accessibility`, and `SEO` tests
using Google [Lighthouse](https://developers.google.com/web/tools/lighthouse) (don't worry about the PWA test, and don't worry about scores for mobile devices).
Test early and often so that fixing problems doesn't lead to suffering at the end of the assignment.

Deliverables
---

Do the following to complete this assignment:

1. Implement your project with the above requirements. A good potential starting point is to use the "hello-express" project template inside of Glitch; this appears as an option when you hit the "New Project" button. Use the work you did in the last assignment as a reference to implement functionality.
2. If you developed your project locally, deploy your project to Glitch (unless completing the alternative server technical acheivement described below), and fill in the appropriate fields in your package.json file.
3. Test your project to make sure that when someone goes to your main page on Glitch, it displays correctly.
4. Ensure that your project has the proper naming scheme `a3-yourfirstname-yourlastname` so we can find it.
5. Fork this repository and modify the README to the specifications below.
6. Create and submit a Pull Request to the original repo. Name the pull request using the following template: `a3-firstname-lastname`.

Acheivements
---

Below are suggested technical and design achievements. You can use these to help boost your grade up to an A and customize the
assignment to your personal interests, for a maximum twenty additional points and a maximum grade of a 100%.
These are recommended acheivements, but feel free to create/implement your own... just make sure you thoroughly describe what you did in your README,
why it was challenging, and how many points you think the achievement should be worth.
ALL ACHIEVEMENTS MUST BE DESCRIBED IN YOUR README IN ORDER TO GET CREDIT FOR THEM.

*Technical*
- (10 points) Implement OAuth authentication, perhaps with a library like [passport.js](http://www.passportjs.org/).
*You must either use Github authenticaion or provide a username/password to access a dummy account*.
Course staff cannot be expected, for example, to have a personal Facebook, Google, or Twitter account to use when grading this assignment.
Please contact the course staff if you have any questions about this. THIS IS THE HARDEST ACHEIVEMENT OFFERED IN WEBWARE. You have been warned!
- (5 points) Instead of Glitch, host your site on a different service like [Heroku](https://www.heroku.com) or [Digital Ocean](https://www.digitalocean.com). Make sure to describe this a bit in your README. What was better about using the service you chose as compared to Glitch? What (if anything) was worse?
- (5 points) Get 100% (not 98%, not 99%, but 100%) in all four lighthouse tests required for this assignment.

*Design/UX*
- (10 points) Make your site accessible using the [resources and hints available from the W3C](https://www.w3.org/WAI/), Implement/follow twelve tips from their [tips for writing](https://www.w3.org/WAI/tips/writing/), [tips for designing](https://www.w3.org/WAI/tips/designing/), and [tips for development](https://www.w3.org/WAI/tips/developing/). *Note that all twelve must require active work on your part*.
For example, even though your page will most likely not have a captcha, you don't get this as one of your twelve tips to follow because you're effectively
getting it "for free" without having to actively change anything about your site.
Contact the course staff if you have any questions about what qualifies and doesn't qualify in this regard.
List each tip that you followed and describe what you did to follow it in your site.
- (5 points) Describe how your site uses the CRAP principles in the Non-Designer's Design Book readings.
Which element received the most emphasis (contrast) on each page?
How did you use proximity to organize the visual information on your page?
What design elements (colors, fonts, layouts, etc.) did you use repeatedly throughout your site?
How did you use alignment to organize information and/or increase contrast for particular elements.
Write a paragraph of at least 125 words *for each of four principles* (four paragraphs, 500 words in total).

Sample Readme (delete the above when you're ready to submit, and modify the below so with your links and descriptions)
---

## Your Web Application Title

your glitch (or alternative server) link e.g. http://a3-charlie-roberts.glitch.me

Include a very brief summary of your project here. Images are encouraged, along with concise, high-level text. Be sure to include:

- the goal of the application
- challenges you faced in realizing the application
- what authentication strategy you chose to use and why (choosing one because it seemed the easiest to implement is perfectly acceptable)
- what CSS framework you used and why
- include any modifications to the CSS framework you made via custom CSS you authored
- the five Express middleware packages you used and a short (one sentence) summary of what each one does. If you use a custom function for *one* (and one alone) middleware please
add a little more detail about what it does.

## Technical Achievements
- **Tech Achievement 1**: I used OAuth authentication via the GitHub strategy
- **Tech Achievement 2**: Instead of Glitch I used Heroku

### Design/Evaluation Achievements
- **Design Achievement 1**: I followed the following tips from the W3C Web Accessibility Initiative...
- **Design Achievement 1**: I followed the following tips from the W3C Web Accessibility Initiative:

- Provide clear and consistent navigation options: Navigation on my web application is straightforward: login -> user page (where you can logout) and if you logout -> login page.
- Content is clear and concise - Login page has only button: Login via github, user page has only functionality that I wrote above: create/delete/edit and logout.
- Ensure that form elements include clearly associated labels - I have only one form and it has only one entry which is content that is supposed to be in the note (and it has label on it)
- Identifiable Feedback for User - in case of any error on my web application the message with error will pop-up, and say how to handle the error. And in case if note is empty and user will try to add it, the message will also pop-up.
- Provide clear and consistent navigation options - as stated above, navigation includes only two pages which are: login and user page which is pretty straightforward
- Use headings and spacing to group related content - navigation bar has the heading as well as the table of notes.
- Provide informative, unique page titles - Each page title has unique name.
- Help users avoid and correct mistakes - I have error messages that will pop-up in case of any errors.
40 changes: 40 additions & 0 deletions auth/auth.controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import {authService} from "./auth.service.js";

class AuthController {

async login (req, res) {
try {

const authData = authService.login()

res.render('login', {authData})

}catch (e) {
console.log(e)
res.status(500).json({message: 'error', error: e})
}
}

async success (req, res) {
try {

const {code} = req.query

if(!code){
return res.redirect('/auth/login')
}

const token = await authService.success(code)

res.cookie('gh_token', token, {maxAge: 60 * 60 * 1000, httpOnly: true})

return res.redirect('/')

}catch (e) {
console.log(e)
res.status(500).json({message: 'error', error: e})
}
}
}

export const authController = new AuthController()
11 changes: 11 additions & 0 deletions auth/auth.route.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import {Router} from 'express'
import {authController} from "./auth.controller.js";

const router = Router()

router.get('/auth/login', authController.login)

router.get('/auth/success', authController.success)


export default router
36 changes: 36 additions & 0 deletions auth/auth.service.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import {GH_AUTH_DATA} from "../config/env.config.js";
import {userService} from "../user/user.service.js";

class AuthService {

login () {
return {
client_id: GH_AUTH_DATA.client_id,
redirect_uri: GH_AUTH_DATA.redirect_uri
}
}

async success (code) {

const token = await userService.getGhToken(code)

const data = await userService.getGhUser(token)

const user = await userService.getOne({username: data.login})

if(!user){

await userService.create({
username: data.login,
gh_id: data.id,
avatar_url: data.avatar_url
})

}

return token
}

}

export const authService = new AuthService()
14 changes: 14 additions & 0 deletions config/env.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@


const GITHUB_CLIENT_SECRET = process.env.GITHUB_CLIENT_SECRET
const GITHUB_CLIENT_ID = process.env.GITHUB_CLIENT_ID
const GITHUB_REDIRECT_URI = process.env.GITHUB_REDIRECT_URI

export const GH_AUTH_DATA = {
client_secret: GITHUB_CLIENT_SECRET,
client_id: GITHUB_CLIENT_ID,
redirect_uri: GITHUB_REDIRECT_URI
}

export const MONGO_URI = process.env.MONGO_URI

10 changes: 10 additions & 0 deletions error/404.route.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import {Router} from 'express'

const router = Router()

router.get('*', (req, res) => {
res.render('errorPage')
})


export default router
55 changes: 55 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import 'dotenv/config';
import express from 'express';
import mongoose from 'mongoose';
import cors from 'cors';
import * as path from 'path';
import { fileURLToPath } from 'url';
import { dirname } from 'path';
import cookieParser from 'cookie-parser';
import notesRoutes from './todos/todos.route.js'
import errorRoutes from './error/404.route.js'
import authRoutes from './auth/auth.route.js'
import {MONGO_URI} from "./config/env.config.js";

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

const app = express()

// middlewares
app.use(cors())
app.use(cookieParser())
app.use(express.json())
app.use('/public', express.static('public'));

app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'ejs')

const PORT = process.env.PORT || 5000

app.use('/', notesRoutes)
app.use('/', authRoutes)
app.use('/', errorRoutes)

const start = async () => {

try {
await mongoose.connect(MONGO_URI, {
useNewUrlParser: true
}, (err) => {
if(err){
console.log('Error db connect')
}else {
console.log('db connected')
}
})

app.listen(PORT, () => {
console.log(`Server has been started in PORT ${PORT}`)
})
}catch (e) {
console.log('Server start error')
}
}

start()
29 changes: 29 additions & 0 deletions middlewares/auth.middleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import {userService} from "../user/user.service.js";

export async function authMiddleware (req, res, next){
if(req.method === 'OPTIONS'){
next()
}

try {

const cookies = req.cookies;

if(!cookies || !cookies.gh_token){
return res.redirect('/auth/login')
}

const user = await userService.getUserByToken(cookies.gh_token)

if(!user){
return res.redirect('/auth/login')
}

req.user = user

next()

} catch (error) {
return res.redirect('/auth/login')
}
}
Loading