Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const express = require('express')
- const mongoose = require('mongoose')
- const Schema = mongoose.Schema
- let UserSchema = new Schema ({
- username: {
- type: String,
- unique: [true, "This username is taken."],
- trim: true
- },
- email: {
- type: String,
- unique: [true, "This email is already being used."],
- trim: true
- },
- password: {
- type: String,
- trim: true
- }
- }, {
- timestamps: true,
- favorites: []
- })
- // first parameter is the name of the collection! If does not exist, will be created!
- const User = mongoose.model('users', UserSchema)
- module.exports = User
- router.post('/signup/users', (req, res, next) => {
- req.checkBody('username', 'Username field cannot be empty.').notEmpty()
- req.checkBody('username', 'Username must be between 4-30 characters long.').len(4, 30)
- req.checkBody('email', 'The email you entered is invalid, please try again.').isEmail()
- req.checkBody('email', 'Email address must be between 4-100 characters long, please try again.').len(4, 100)
- req.checkBody('password', 'Password must be between 8-100 characters long.').len(8, 100)
- // req.checkBody('password', 'Password must include one lowercase character, one uppercase character, a number, and a special character.').matches(/^(?=.*d)(?=.*[a-z])(?=.*[A-Z])(?!.* )(?=.*[^a-zA-Z0-9]).{8,}$/, 'i')
- req.checkBody('passwordMatch', 'Password must be between 8-100 characters long.').len(8, 100)
- req.checkBody('passwordMatch', 'Passwords do not match, please try again.').equals(req.body.password)
- // Additional validation to ensure username is alphanumeric with underscores and dashes
- req.checkBody('username', 'Username can only contain letters, numbers, or underscores.').matches(/^[A-Za-z0-9_-]+$/, 'i')
- const errors = req.validationErrors()
- if(errors) {
- res.render('signup', {
- errors: errors
- })
- } else {
- let password = req.body.password
- bcrypt.hash(password, saltRounds, (err, hash) => {
- user = new User()
- user.username = req.body.username
- user.email = req.body.email
- user.password = hash
- user.save((err, result) => {
- if(err) {
- console.log(err)
- } else {
- User.find({}).sort({ _id:-1 }).limit(1)
- .exec((err, newuser) => {
- if (err) {
- console.log(err)
- } else {
- userId = ObjectId(newuser.id)
- // logins user through passport function
- req.login(userId, (err) => {
- if (err) {
- console.log("Login error: " + err)
- } else {
- res.redirect('/home')
- }
- })
- }
- })
- .catch(next)
- }
- })
- })
- }
- })
- kill -2 `pgrep mongo`
Add Comment
Please, Sign In to add comment