Skip to content

Commit

Permalink
Oauth2
Browse files Browse the repository at this point in the history
  • Loading branch information
rabarbar15 committed Jun 8, 2024
1 parent 9a60e39 commit 439de59
Show file tree
Hide file tree
Showing 27 changed files with 7,005 additions and 0 deletions.
122 changes: 122 additions & 0 deletions Zad8 - Oauth2/backend/authController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
const { User } = require('./model')
const jwt = require('jsonwebtoken')
// const bcrypt = require('bcrypt')

const handleErrors = (err) => {
let errors = { email: '', password: '' }

if (err.message.includes('Validation error')) {
Object.values(err.errors).forEach(error => {
errors[error.path] = error.message
console.log(errors);
})
}

if (err.message.includes('Incorrect password')) {
errors.password = 'Incorrect password'
}

if (err.message.includes('User not found')) {
errors.email = 'User not found'
}

return errors
}

const maxAge = 3 * 24 * 60 * 60

const createToken = (id) => {
return jwt.sign({ id }, 'my big secret', {
expiresIn: maxAge
})
}

exports.signup = async (req, res) => {

try {
const { email, password } = req.body;

if ( !email || !password) {
return res.status(400).json({ error: 'Wszystkie pola są wymagane' });
}

console.log(email, password);

const user = await User.create({
email: email,
password: password
})
// console.log(user.id);
const token = createToken(user.id)
res.cookie('jwt', token, { httpOnly: true, maxAge: maxAge * 1000})

res.status(201).json({ user: user.id })

} catch (error) {
console.log(error);
const errors = handleErrors(error)
console.error("Błąd przy rejestracji uzytkownika", errors)
res.status(400).json({errors})
}
}


exports.signin = async (req, res) => {

try {
const { email, password} = req.body;

if (!email || !password) {
return res.status(400).json({ error: 'Wszystkie pola są wymagane' });
}

try {
const user = await User.login(email, password)
console.log(user)

const token = createToken(user.id)
res.cookie('jwt', token, { httpOnly: true, maxAge: maxAge * 1000})

res.status(201).json({ user: user.id })
} catch (error) {
console.log(error);
const errors = handleErrors(error)
res.status(400).json({errors})
}

} catch (error) {
const errors = handleErrors(error)
console.error("Błąd przy logowaniu uzytkownika", errors)
res.status(400).json({errors})
}
}

exports.authConfirm = (req, res) => {
res.status(201).json({ auth: 'Signed in' })
}

exports.getUser = (req, res) => {

const token = req.cookies.jwt

if (token) {
jwt.verify(token, 'my big secret', async (err, decodedToken) => {
if (err) {
res.status(401).json({ message: 'Unauthorized' });

} else {
let user = await User.findByPk(decodedToken.id)
console.log('user id:', user.id)
res.send(user)
}
})
} else {
res.status(401).json({ message: 'Unauthorized' });
}
}

exports.logout = (req, res) => {
// replace jwt with a blank cookie
res.cookie('jwt', '', { maxAge: 1 })
res.send('Logged out')
}
23 changes: 23 additions & 0 deletions Zad8 - Oauth2/backend/authMiddleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
const jwt = require('jsonwebtoken')
const { User } = require('./model')

const requireAuth = (req, res, next) => {
const token = req.cookies.jwt

if (token) {
jwt.verify(token, 'my big secret', (err, decodedToken) => {
if (err) {

res.status(401).json({ message: 'Unauthorized' });
} else {

next();
}
})
} else {
res.status(401).json({ message: 'Unauthorized' });
}
}


module.exports = { requireAuth }
Binary file added Zad8 - Oauth2/backend/data.sqlite
Binary file not shown.
9 changes: 9 additions & 0 deletions Zad8 - Oauth2/backend/database.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
const { Sequelize } = require('sequelize')


const sequelize = new Sequelize({
dialect: 'sqlite',
storage: 'data.sqlite'
})

module.exports = sequelize
67 changes: 67 additions & 0 deletions Zad8 - Oauth2/backend/model.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
const { DataTypes } = require('sequelize');
const sequelize = require('./database');
const bcrypt = require('bcrypt')


const User = sequelize.define('User', {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
},

email: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
validate: {
isEmail: {
args: true,
msg: 'Enter a valid email'
}
}
},

password: {
type: DataTypes.STRING,
allowNull: false,
validate: {
len: {
args: [4],
msg: 'Password must be at least 4 characters long'
}
}
}
}

);

User.login = async function(email, password) {
const user = await User.findOne({
where: {
email: email
}
})

if (user) {
// console.log(user.password);
const auth = await bcrypt.compare(password, user.password)
if (auth) {
return user
}
throw Error('Incorrect password')
}
throw Error('User not found')
}


User.beforeCreate(async (user, options) => {
const salt = await bcrypt.genSalt();
user.password = await bcrypt.hash(user.password, salt)
console.log('Hashed: ', user.password);
});




module.exports = { User };
Loading

0 comments on commit 439de59

Please sign in to comment.