# Back End Setup

## 1.  Create Mongoose User model

{% code title="api/models/Users.js" %}

```javascript
var Mongoose = require('mongoose');
var Schema = Mongoose.Schema;

// Create Schema Object
var UserSchema = new Schema({ 
    firstName: { type: String }, 
    lastName: { type: String }, 
    username: { type: String, default: '' }, 
    email: { type: String }, 
    password: { type: String }, 
    resetToken: { type: String }, 
    resetTokenExpires: { type: Date }, 
    status: { type: Boolean, default: true }, 
    googleId: { type: String }, 
    profileImage: { type: String, default: '' }
});

// This will creates database collection named "Users" in the Database
var Users = Mongoose.model('Users', UserSchema);

module.exports = Users;

```

{% endcode %}

## &#x20;2. Set up API route, ensuring compatibility with passportJS

Register requires a passport.authenticate function, along with any route in which the username/password needs to be explicitly checked against.

For any routes that just needs to check whether the user is logged in, it can just use passportJS isAuthenticated().

{% code title="api/routes/index.js" %}

```javascript
var express = require('express');
var router = express.Router();
var isAuthenticated = require('../utils/authentication');
var User = require('../models/Users');
var UserDetails = require('../models/UserDetails');

module.exports = function(passport) {
    router.post('/signup', function(req, res, next) { 
        // this will pass the function to passport (api/passport/signup.js)
        // what is returned in the above function will be accessible in the callback
        passport.authenticate('signup', function(err, user, info) { 
            if (err) { 
                return next(err); 
            } else if (!user) { 
                // if no user was passed back
                return res.json({ message: info.message }); 
            } else { 
                // if user was found, log in user using passport logIn()
                req.logIn(user, function(err) { 
                    if (err) { 
                        return next(err); 
                    } 
                    UserDetails.findOne({ username: user.username }, function( err, userDetail ) { 
                        if (err) { 
                            return res.json({ error: err }); 
                        } 
                        return res.json({ user: user, userDetail: userDetail, message: info.message }); 
                    }); 
                }); 
            } 
        })(req, res, next); 
    });
}

```

{% endcode %}

{% code title="src/passport/signup,js" %}

```javascript
var LocalStrategy = require('passport-local').Strategy;
var User = require('../models/Users');
var bCrypt = require('bcrypt-nodejs');
var UserDetails = require('../models/UserDetails');

passport.use( 'signup', new LocalStrategy( { 
 usernameField: 'email', 
 passwordField: 'password', 
 passReqToCallback: true 
 }, function(req, username, password, done) { 
 
  findOrCreateUser = function() { 
   User.findOne(
    { $or: [{ email: username }, { username: req.body.username }] }, 
    function(err, user) { 
    
    if (err) { return done(err); } 
    
    //  User already exists with this email or username
    if (user) { return done(null, false, { 
     message: 'User already exists with this email or username' }); 
    } else { 
    
     var newUser = new User();
     
     newUser.username = req.body.username; 
     newUser.password = createHash(password); 
     newUser.email = username; 
     newUser.firstName = req.body.firstName; 
     newUser.lastName = req.body.lastName;
     
     newUser.save(function(err) { 
      if (err) { throw err; } 
      
      var newUserDetails = new UserDetails({ 
        _id: newUser._id, 
        username: newUser.username 
      }); 
      
      newUserDetails.save(function(err, userDetail) { 
       if (err) { throw err; }  
      }); 
      
      return done(null, newUser, { message: 'User Registration Succesful' }); 
      
     }); 
    } 
   } 
  ); 
 }; 
 // Delay the execution of findOrCreateUser and execute the method 
 // in the next tick of the event loop 
 process.nextTick(findOrCreateUser); 
} 
) 
);

// Generates hash using bCrypt 
 var createHash = function(password) { 
  return bCrypt.hashSync(password, bCrypt.genSaltSync(10), null); 
 };

};
```

{% endcode %}

## 3. Testing With Postman

Use Postman App to test the backend routes.

![Postman Testing](/files/-LBi6xrsJxD9Aw5XWkA8)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://project-match.gitbook.io/project-match/untitled-1/back-end-setup.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
