I'm using Linux and, I'm trying to insert my Textbox values into mysql via sails.js. When I surfing the net, I didn't get any clear answer.
I have attached My Controller for create function
module.exports = {
create :function(req,res){
if(req.method=="POST"&&req.param("User",null)!=null)
{
var insert = "INSERT INTO User VALUES("+req.params.userId+",'"+req.params.loginName+"','"+req.params.userName+"','"+req.params.password+"','"+req.params.userMail+"')";
User.query(insert,function(err,record){
if(err)
{
console.log("Error");
}
else
{
console.log(record);
res.redirect('User/index');
}
});
}
},
this is my create.ejs
<form action="/user/create" method="POST">
<table>
<tr><td>UserId:<td><input type="text" name="User[userId]"><br/>
<tr><td>LoginName:<td><input type="text" name="User[loginName]"><br/>
<tr><td>UserName:<td><input type="text" name="User[userName]"><br/>
<tr><td>Password:<td><input type="text" name="User[password]"><br/>
<tr><td>UserMail:<td><input type="text" name="User[userMail]"><br/>
<tr><td><td><input type="submit" value="Register">
</form>
connection.js is:
module.exports.connections = {
mysql: {
module : 'sails-mysql',
host : 'localhost',
port : 3306,
user : 'root',
password : 'assyst',
database : 'User'
},
};
How to do basic crud operations in sails.js with mysql.
Expect if you create User API by sails generate api user it will automatically UserController.js at api/controllers and User.js at api/models.
Modify User.js at your api/models/User.js to
module.exports = {
attributes : {
userId : {type: 'string'},
loginName : {type: 'string'},
userName : {type: 'string'},
password : {type: 'string'},
userMail : {type: 'string'}
}
};
By default, it expose Blueprint API and you can POST something to user model by:
<form action="/user" method="POST">
<table>
<tr><td>UserId:<td><input type="text" name="userId"><br/>
<tr><td>LoginName:<td><input type="text" name="loginName"><br/>
<tr><td>UserName:<td><input type="text" name="userName"><br/>
<tr><td>Password:<td><input type="text" name="password"><br/>
<tr><td>UserMail:<td><input type="text" name="userMail"><br/>
<tr><td><td><input type="submit" value="Register">
</form>
That's the basic CRUD at Sails.
Here is my insert operation in sails.js with Mysql
Insert:function(req,res)
{
if(req.method=="POST")
{
console.log("Post");
var userId = req.param("userId");
var userName = req.param("userName");
var loginName =req.param("loginName");
var password =req.param("password");
var userMail =req.param("userMail");
console.log(userName);
var insert = "INSERT INTO User(UserId,LoginName,UserName,password,UserMail) VALUES("+userId+",'"+loginName+"','"+userName+"','"+password+"','"+userMail+"')";
User.query(insert,function(err,record)
{
if(err)
{
console.log(err);
}
else
{
console.log(record);
res.redirect('User/index');
}
});
}
else
{
res.render("create");
}
},
Related
I have create a login form with two fields
a field where the user can select their university
a field where the user can enter their university email address
I use next-auth's Email Provider under the hood, so when they fill out those two fields and click on "sign up", a document will automatically be created by default in my MongoDB "users" collection that looks like this
email: 'theuseremail#something.com',
emailVerified: '2022-07-16T11:54:06.848+00:00'
and the user gets an email with a magic sign link to sign in to the website.
My problem is the following:
I want to be able to store not just the user email but also the university they selected when filling out the sign up form. But the object that gets created by default in my MongoDB only has the "email" and the "emailVerified" fields. I cannot find a way to capture other data (e.g. the user's selected university) to create the user in the database.
Is there any obvious way of doing so that I am missing? I have looked around but couldn't find any working example of this! Any help is appreciated.
This is my pages/api/[...nextAuth].js file:
import NextAuth from "next-auth"
import nodemailer from 'nodemailer'
import EmailProvider from 'next-auth/providers/email'
import { MongoDBAdapter } from "#next-auth/mongodb-adapter"
import clientPromise from "../../../utils/mongoClientPromise"
const THIRTY_DAYS = 30 * 24 * 60 * 60
const THIRTY_MINUTES = 30 * 60
export default NextAuth({
secret: process.env.NEXTAUTH_SECRET,
session: {
strategy: 'jwt',
maxAge: THIRTY_DAYS,
updateAge: THIRTY_MINUTES
},
adapter: MongoDBAdapter(clientPromise),
providers: [
EmailProvider({
server: {
host: process.env.EMAIL_SERVER_HOST,
port: process.env.EMAIL_SERVER_PORT,
auth: {
user: process.env.EMAIL_SERVER_USER,
pass: process.env.EMAIL_SERVER_PASSWORD
}
},
from: process.env.EMAIL_FROM,
async sendVerificationRequest ({
identifier: email,
url,
provider: { server, from }
}) {
const { host } = new URL(url)
const transport = nodemailer.createTransport(server)
await transport.sendMail({
to: email,
from,
subject: `Sign in to ${host}`,
text: text({ url, host }),
html: html({ url, host, email })
})
}
})
],
pages: {
signIn: '/login',
}
})
function html ({ url, host, email }) {
const escapedEmail = `${email.replace(/\./g, '.')}`
const escapedHost = `${host.replace(/\./g, '.')}`
// Your email template here
return `
<body>
<h1>Your magic link! 🪄</h1>
<h3>Your email is ${escapedEmail}</h3>
<p>
Sign in to ${escapedHost}
</body>
`
}
// Fallback for non-HTML email clients
function text ({ url, host }) {
return `Sign in to ${host}\n${url}\n\n`
}
This is my Login page in pages/login.tsx:
import { Row, Col, Button, Input, Form, Space } from "antd";
import { useSession, signIn } from "next-auth/react";
import { getCsrfToken } from "next-auth/react"
import { useRouter } from 'next/router';
import { useState } from "react";
import UniversitySearchAndSelectDropdown from "../components/UniversitySearchAndSelectDropdown";
import data from '../mock_api_payload.json'
export default function LoginPage({ csrfToken }) {
const navigate = useRouter();
const { data: session } = useSession()
const [selectedUniversityId, setSelectedUniversityId] = useState('');
const [form] = Form.useForm();
if (session) {
navigate.push("/")
}
if (!session) {
return (
<>
<Row justify="center" style={{marginTop: '2rem'}}>
<Col>
<form method="post" action="/api/auth/signin/email">
<input name="csrfToken" type="hidden" defaultValue={csrfToken} />
<Row justify="center">
<Col>
<Space direction="vertical">
<Input
placeholder="Enter your university email address"
type="email"
id="email"
name="email"
/>
</Space>
</Col>
</Row>
<Row justify="center" style={{marginTop: '1rem'}}>
<Col>
<Button
htmlType="submit"
shape="round"
type="primary"
>Sign in</Button>
</Col>
</Row>
</form>
</Col>
</Row>
</>
)
}
};
export async function getServerSideProps(context: any) {
const csrfToken = await getCsrfToken(context)
return {
props: { csrfToken },
}
}
Thank you!
I want to load data with a GET request and fill the data to the input data attributes at vue.js 3 like
<input id="name" type="text" v-bind:placeholder="$t('message.NamePlaceholder')" value="{{ name }}" required>
and this is my script part
<script>
export default {
data () {
return {
userInformation: {},
name: "",
}
},
mounted () {
this.getUserInformation();
},
methods () {
getUserInformation() {
this.$axios({
method: 'get',
url: 'http://127.0.0.1:8000/api/get_user_information',
}).then(response => {this.userInformation = response.data});
this.name = this.userInformation.Name;
}
},
}
But the input field contains only {{ name }}. I tried also v-bind:value, but this didn't solve the problem.
Whenever you need to bind values to attributes {{}} are unnecessary. You can just write v-bind:value="name" or :value="name"
E.g.:
<input id="name" type="text" :placeholder="message.NamePlaceholder" :value="name" required></input>
The mistake was that I have to set the variable this.name at the axios command:
this.$axios({
method: 'get',
url: 'http://127.0.0.1:8000/api/get_user_information',
}).then(response => {
this.userInformation = response.data;
this.name = this.userInformation.Name;
});
I'm working my way through a tutorial regarding passport.js and authentication and I'm coming unstuck. I'm just testing the signup function at the moment and my app is freezing. Here's my server file:
var express = require('express'),
app = express(),
mongoose = require('mongoose'),
passport = require('passport'),
flash = require('connect-flash'),
morgan = require('morgan'),
cookieParser = require('cookie-parser'),
bodyParser = require('body-parser'),
session = require('express-session');
// configDB = require('./config/database.js');
mongoose.connect('mongodb://localhost/Auth_practice');
require('./config/passport')(passport); // pass passport for config
// set up express app
app.use(morgan('dev')); // log every request to the console
app.use(cookieParser()); // read cookies (required for auth)
app.use(bodyParser()); // get information from html forms
app.set('view engine', 'ejs') // set up ejs for templating
// required for passport
app.use(session({secret: 'ilovethetoonandrafa'})); // session secret
app.use(passport.initialize());
app.use(passport.session()); // for persistent login
sessions
app.use(flash());
// routes
require('./app/routes.js')(app, passport); // load our routes
and pass in passport
app.listen(process.env.PORT, process.env.IP, function(){
console.log("Server has started")
});
Here's my user model:
// load the things we need
var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');
// define schema for our user model
var userSchema = mongoose.Schema({
local :{
email : String,
password : String,
},
facebook :{
id : String,
token : String,
email : String,
name : String
},
twitter :{
id : String,
token : String,
displayName : String,
username : String
},
google :{
id : String,
token : String,
email : String,
name : String
}
});
// method =========================
// generate a hash
userSchema.methods.generateHash = function(password) {
return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
};
// check if password is valid
userSchema.methods.validPassword = function(password) {
return bcrypt.compareSync(password, this.local.password);
};
// create the model for users and expose it to our app
module.exports = mongoose.model('User', userSchema);
My strategy setup:
// config/passport.js
// load all the things we need
var LocalStrategy = require('passport-local').Strategy;
// load up the user model
var User = require('../app/models/user');
// expose this function to our app using module.exports
module.exports = function(passport) {
// =========================================================================
// passport session setup ==================================================
// =========================================================================
// required for persistent login sessions
// passport needs ability to serialize and unserialize users out of session
// used to serialize the user for the session
passport.serializeUser(function(user, done) {
done(null, user.id);
});
// used to deserialize the user
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
// =========================================================================
// LOCAL SIGNUP ============================================================
// =========================================================================
// we are using named strategies since we have one for login and one for signup
// by default, if there was no name, it would just be called 'local'
passport.use('local-signup', new LocalStrategy({
// by default, local strategy uses username and password, we will override with email
usernameField : 'email',
passwordField : 'password',
passReqToCallback : true // allows us to pass back the entire request to the callback
},
function(req, email, password, done) {
// asynchronous
// User.findOne wont fire unless data is sent back
process.nextTick(function() {
// find a user whose email is the same as the forms email
// we are checking to see if the user trying to login already exists
User.findOne({ 'local.email' : email }, function(err, user) {
// if there are any errors, return the error
if (err)
return done(err);
// check to see if theres already a user with that email
if (user) {
return done(null, false, req.flash('signupMessage', 'That email is already taken.'));
} else {
// if there is no user with that email
// create the user
var newUser = new User();
// set the user's local credentials
newUser.local.email = email;
newUser.local.password = newUser.generateHash(password);
// save the user
newUser.save(function(err) {
if (err)
throw err;
return done(null, newUser);
});
}
});
});
}));
};
And my route for signup
app.post('/signup', passport.authenticate('local-signup', {
successRedirect: '/profile', // redirect to the secure profile of the
user
failureRedirect: '/signup', // redirect to signup page if failure
failureFlash: true // allow flash messages
}));
Finally here's the signup form:
<!-- views/signup.ejs -->
<!doctype html>
<html>
<head>
<title>Node Authentication</title>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css"> <!-- load bootstrap css -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css"> <!-- load fontawesome -->
<style>
body { padding-top:80px; }
</style>
</head>
<body>
<div class="container">
<div class="col-sm-6 col-sm-offset-3">
<h1><span class="fa fa-sign-in"></span> Signup</h1>
<!-- show any messages that come back with authentication -->
<% if (message.length > 0) { %>
<div class="alert alert-danger"><%= message %></div>
<% } %>
<!-- LOGIN FORM -->
<form action="/signup" method="post">
<div class="form-group">
<label>Email</label>
<input type="text" class="form-control" name="email">
</div>
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" name="password">
</div>
<button type="submit" class="btn btn-warning btn-lg">Signup</button>
</form>
<hr>
<p>Already have an account? Login</p>
<p>Or go home.</p>
</div>
</div>
</body>
Can anyone see what's causing the app to freeze?
I'm develop in ng2 rc4 and my User data stored Mongo DB. User's can edit their data in my page, but my editing page hav got a problem. My source looks like this:
import { User } from './user.service.ts';
#component(
selector: 'edit-user',
template: `
Email : <input type="text" [(ngModel)]="userInfo.email"><br />
Name : <input type="text" [(ngModel)]="userInfo.name"><br />
Address : <input type="text" [(ngModel)]="userInfo.address"><br />
Tel :
<input type="text" [(ngModel)]="userInfo.tel.tel1">-
<input type="text" [(ngModel)]="userInfo.tel.tel2">-
<input type="text" [(ngModel)]="userInfo.tel.tel3"><br />
<button>Submit</button>
`,
providers: [ User ]
)
export class EditUser {
private userInfo: any = {
'email': '',
'name': '',
'address': '',
'tel': {
'tel1': '',
'tel2': '',
'tel3': ''
}
};
constructor(private user: User) {
}
ngOnInit() {
this.getUser();
}
getUser() {
this.user.getUser( ... )
.then(res => {
...
// case 1
// res = {'email': 'a#a.a', 'name': 'NameA', 'address': 'aaa', 'tel': {'tel1': '1', 'tel2': '2', 'tel3': '3'}};
// case 2
// res = {'email': 'b#b.b', 'name': 'NameB'};
this.userInfo = res;
...
})
.catch( ... )
}
}
Everything is okay when in case 1 but in case 2 there is no tel object and input tag throws error because of the missing tel object in res. The user was not entering tel information in the case 2. So it is a 2 way binding error: undefined tel property of userInfo. don't expression, don't enter the tel.tel1 property.
I can't change mongoDB and json hierarchy. How can I resolve this?
Assign empty object to tel if empty
res.tel = res.tel || {};
this.userInfo = res;
I'm using AngularJS v1.2.13 to create a page with a form which will download a user's file on click.
I'm using $sce to enable the injection of the file URL which works fine.
However, the loading of the resource disables the form submit. I'm sure it has to do with the resource load because when I remove the load and hardcode the url it works fine. I've also created a JSFiddle without it and have not been able to reproduce the problem there.
Any ideas on why this is happening and how it can be fixed?
HTML:
<div ng-controller="viewProfileController" data-ng-init="findOne();">
<form method="get" action="{{downloadFileURL}}">
<button type="submit" class="no-button comment-small" >
Download File
</button>
</form>
</div>
Controller:
'use strict';
angular.module('bop.viewProfile').controller('viewProfileController', [
'$scope', 'Users', '$sce', '$routeParams',
function($scope, Users, $sce, $routeParams) {
$scope.downloadFileURL = '';
// Find current user
$scope.findOne = function() {
Users.get({
userId: $routeParams.userId
}, function(user) {
$scope.user = user;
$scope.downloadFileURL = $sce.trustAsResourceUrl($scope.user.file.url);
});
};
}]);
Users Service:
var userServices = angular.module('bop.users', ['ngResource']);
userServices.factory('Users', ['$resource', function($resource) {
return $resource(
'users/:userId',
{ userId: '#_id' },
{ update: { method: 'PUT' } }
);
}]);