method on the server side is invoked two times, why? - javascript

I have problem with method on the server side. It is invoked two times, but it should only one. Error occur when I change password. To change password I use Accounts.setpassword(). Below code of that method:
import { Meteor } from 'meteor/meteor';
import { check } from 'meteor/check';
import { TAPi18n } from 'meteor/tap:i18n';
import { Accounts } from 'meteor/accounts-base';
import _ from 'lodash';
Meteor.methods({
'users/change-user-settings'(formData) {
if (!this.userId) {
throw new Meteor.Error(401, TAPi18n.__('errors.you_are_not_logged'));
}
check(formData, App.Schemas.userSettingsSchema);
//change password
if (formData.password) {
Accounts.setPassword(this.userId, formData.password, {logout: false});
}
//change email
if (formData.email) {
Meteor.users.update({_id: this.userId}, {
$set: {
'emails.0.address': formData.email
}
});
}
//change phone number
if (formData.phoneNumber) {
Meteor.users.update({_id: this.userId}, {
$set: {
'phoneNumber': formData.phoneNumber
}
});
}
return true;
}
});
My autoform form and schema to it:
<template name="userSettingsTemplate">
<div class="user-settings-form-wrapper">
<h4>Change settings</h4>
{{ #autoForm id="userSettingsForm" type="method" meteormethod="users/change-user-settings" schema=getUserSettingsSchema class="form-horizontal"}}
{{ > afQuickField name="password" label="Change password: " template="bootstrap3-horizontal" label-class="col-xs-6" input-col-class="col-xs-6"}}
{{ > afQuickField name="passwordConfirmation" label="Confirm password: " template="bootstrap3-horizontal" label-class="col-xs-6" input-col-class="col-xs-6"}}
{{ > afQuickField name="email" label="E-mail: " template="bootstrap3-horizontal" label-class="col-xs-6" input-col-class="col-xs-6"}}
{{ > afQuickField name="phoneNumber" label="Phone number: " template="bootstrap3-horizontal" label-class="col-xs-6" input-col-class="col-xs-6"}}
<div class="form-group">
<button type="submit" class="btn btn-primary full-width">Send</button>
</div>
{{ / autoForm }}
</div>
</template>
Schema:
import { SimpleSchema } from 'meteor/aldeed:simple-schema';
import { TAPi18n } from 'meteor/tap:i18n';
import { Meteor } from 'meteor/meteor';
Meteor.startup(() => {
// for running tests this is temporary workaround
try {
SimpleSchema.messages({
"passwordMismatch": "passwords are not the same"
});
}
catch (e) {
console.log(e.message, e.name, e.stack);
}
});
App.Schemas.userSettingsSchema = new SimpleSchema({
password: {
type: String,
optional: true,
min: 6,
autoform: {
type: "password"
}
},
passwordConfirmation: {
type: String,
min: 6,
optional: true,
autoform: {
type: "password"
},
custom: function() {
if (this.value !== this.field('password').value) {
return "passwordMismatch";
}
}
},
email: {
type: String,
optional: true,
regEx: SimpleSchema.RegEx.Email
},
phoneNumber: {
type: String,
optional: true
}
});

Just a side note. Unless I'm missing something here, you should not be using Accounts.setPassword() like that. It's a server side method, so the new password gets sent as plain text over the wire. Instead, take a look at Accounts.changePassword(), which runs on client and is meant to do what you want to do.

Related

Simple validation in vue

I am beginner web developer.
I make my first application in vue project.
I have this code:
<template>
<CRow>
<CCol col="12" lg="6">
<CCard no-header>
<CCardBody>
<h3>
Create Note
</h3>
<CAlert
:show.sync="dismissCountDown"
color="primary"
fade
>
({{ dismissCountDown }}) {{ message }}
</CAlert>
<CInput label="Title" type="text" id="title" placeholder="Title" v-model="note.title"></CInput>
<CInput textarea="true" label="Content" id="content" :rows="9" placeholder="Content.."
v-model="note.content"></CInput>
<CInput label="Applies to date" type="date" id="applies_to_date" v-model="note.applies_to_date"></CInput>
<CSelect id="status_id"
label="Status"
:value.sync="note.status_id"
:plain="true"
:options="statuses"
>
</CSelect>
<CInput label="Note type" type="text" id="note_type" v-model="note.note_type"></CInput>
<template>
<div id="app">
<ckeditor v-model="editorData" :config="editorConfig"></ckeditor>
</div>
</template>
<CButton color="primary" #click="store()">Create</CButton>
<CButton color="primary" #click="goBack">Back</CButton>
</CCardBody>
</CCard>
</CCol>
</CRow>
</template>
import axios from 'axios';
import Vue from 'vue';
import CKEditor from 'ckeditor4-vue';
Vue.use(CKEditor);
export default {
name: 'EditUser',
props: {
caption: {
type: String,
default: 'User id'
},
},
data: () => {
return {
note: {
title: '',
content: '',
applies_to_date: '',
status_id: null,
note_type: '',
},
statuses: [],
message: '',
dismissSecs: 7,
dismissCountDown: 0,
showDismissibleAlert: false,
editorData: '',
editorConfig: {
// The configuration of the editor.
filebrowserImageBrowseUrl: Vue.prototype.$apiAdress+'/api/laravel-filemanager?token=' + localStorage.getItem("api_token"),
filebrowserImageUploadUrl: Vue.prototype.$apiAdress+'/api/laravel-filemanager/upload?type=Images&_token=&token=' + localStorage.getItem("api_token"),
filebrowserBrowseUrl: Vue.prototype.$apiAdress+'/api/laravel-filemanager?type=Files&token=' + localStorage.getItem("api_token"),
filebrowserUploadUrl: Vue.prototype.$apiAdress+'/api/laravel-filemanager/upload?type=Files&_token=&token=' + localStorage.getItem("api_token"),
height: 500,
language: 'pl',
//extraPlugins: 'facebookvideo, youtube, html5video',
editorUrl: "facebookvideo.js",
extraPlugins: 'a11yhelp,about,basicstyles,bidi,blockquote,clipboard,colorbutton,colordialog,contextmenu,copyformatting,dialogadvtab,div,editorplaceholder,elementspath,enterkey,entities,exportpdf,filebrowser,find,flash,floatingspace,font,format,forms,horizontalrule,htmlwriter,iframe,image,indentblock,indentlist,justify,language,link,list,liststyle,magicline,maximize,newpage,pagebreak,pastefromgdocs,pastefromlibreoffice,pastefromword,pastetext,preview,print,removeformat,resize,save,scayt,selectall,showblocks,showborders,smiley,sourcearea,specialchar,stylescombo,tab,table,tableselection,tabletools,templates,toolbar,undo,uploadimage, wysiwygarea,autoembed,image2,embedsemantic',
image2_alignClasses: ['image-align-left', 'image-align-center', 'image-align-right'],
image2_disableResizer: true,
}
}
},
methods: {
goBack() {
this.$router.go(-1)
// this.$router.replace({path: '/users'})
},
store() {
let self = this;
axios.post(this.$apiAdress + '/api/notes?token=' + localStorage.getItem("api_token"),
self.note
)
.then(function (response) {
self.note = {
title: '',
content: '',
applies_to_date: '',
status_id: null,
note_type: '',
};
self.message = 'Successfully created note.';
self.showAlert();
}).catch(function (error) {
if (error.response.data.message == 'The given data was invalid.') {
self.message = '';
for (let key in error.response.data.errors) {
if (error.response.data.errors.hasOwnProperty(key)) {
self.message += error.response.data.errors[key][0] + ' ';
}
}
self.showAlert();
} else {
console.log(error);
self.$router.push({path: 'login'});
}
});
},
countDownChanged(dismissCountDown) {
this.dismissCountDown = dismissCountDown
},
showAlert() {
this.dismissCountDown = this.dismissSecs
},
},
mounted: function () {
let self = this;
axios.get(this.$apiAdress + '/api/notes/create?token=' + localStorage.getItem("api_token"))
.then(function (response) {
self.statuses = response.data;
}).catch(function (error) {
console.log(error);
self.$router.push({path: 'login'});
});
}
}
I need add to my project validation with alert box when input is empty.
I need required for title and content. When user click button "Create" I need check this inputs. If it's empty - then I need show alert().
How can I make it?
Please help me :)
You can make method:
checkInputs() {
if(!this.note.title) {
this.message = 'pls enter title'
this.showAlert()
return true
}
if(!this.note.content) {
this.message = 'pls enter content'
this.showAlert()
return true
}
return false
}
and in store method:
store() {
if(this.checkInputs()) return
...

How to emit and event within a promise in Vuejs [duplicate]

I'm learning on how to render HTML contents in Vuejs I'm trying to build a small input component which gets generated from render function. It looks something like this:
export default {
name: "nits-input",
methods: {
},
props: {
label: String,
hint: String,
error: String,
placeholder: String
},
render (createElement) {
//Help action text
let helpText = this.hint ? createElement('span', { class: 'm-form__help' }, this.hint) : ''
//Error Text
let errorText = this.error ? createElement('span', { class: 'm--font-danger' }, this.error) : ''
return createElement('div', { class: ''}, [
createElement('label', this.label),
createElement('input', {
class: 'form-control m-input',
attrs: { type: this.type, placeholder: this.placeholder },
domProps: { value: self.value},
on: {
input: function (event) {
this.$emit('input', event.target.value)
}
}
}),
helpText, errorText
])
}
}
While calling this component I'm doing below:
<div class="form-group m-form__group">
<nits-input
label="Email Address"
type="email"
hint="We'll never share your email with anyone else."
placeholder="Enter email"
v-model="email"
>
</nits-input>
</div>
<div class="form-group m-form__group">
<nits-input
label="Password"
type="password"
placeholder="Enter password"
v-model="password"
>
</nits-input>
</div>
I want the value to be stored into v-model, to check the values are being set properly I'm using a watch function
watch: {
email () {
console.log('Email v-model defined as '+this.email)
},
password() {
console.log('Password v-model defined as '+this.password)
}
}
But this always gives me error:
Uncaught TypeError: Cannot read property '$emit' of null
I've taken the references from This VueJS Documentation Link. Help me out in this. Thanks.
you should use arrow function since you're loosing the scope inside that callback :
on: {
input:(event)=> {
this.$emit('input', event.target.value)
}
}

Extracting data from an API in typescript vue and to a prop

I need some help guys. Anytime I've done this I've used a v-for and extracted the data manually. The problem I am facing here is that the component I am passing the data to is a custom component already written to accept the data in an :options prop. But all I am getting is "null" for every piece of state.
Here is the template
<WDropDown label="Commissioner" :options="dropdownCommissionerValues" v-model="commissioner1"/>
And the script lang="ts"
// Data Section
apiInvoker= methods; //this is coming from a service file that logs to the API
public commissioner1 = "1";
dropdownCommissionerValues= [];
mounted () {
this.apiInvoker.viewRequestGet("resources/GetCommisionerList").then((response) => {
if(response.data) {
this.dropdownCommissionerValues = response.data.Table;
console.log("My Response is", this.dropdownCommissionerValues);
}
});
}
Inspecting the Vue Dev Tool, and the console, I am connecting to the API and I am getting data in the component. See image below
But this is what I am getting in the browser See image
NOTE, If I hardcode my data in dropdownCommissionerValues as shown below, it get it to work. But I need it to come from the API
this.dropdownCommissionerValues= [
{
value:"1",
text:"Something 1"
},
{
value:"2",
text:"Something 2"
}
]
I assume somehow I have to pass CommissionerId as value and CommissionerName as text because that's how the component reads it? I just can't figure out how
Thanks in advance!
Here is the custom component
<template>
<ValidationProvider :vid="id" :name="id" :rules="rules" v-slot="wDropDown">
<wFormGroup :class="classObject"
:id="groupId('lbl', id)"
:label="label"
:label-for="id"
:label-sr-only="labelSrOnly">
<template v-if="(pagePlaintext || plaintext || isPlaintext) && !dropDownBind">
<b-form-input plaintext
aria-readonly="true"
readonly="readonly"
:aria-label="label"
:data-vv-as="label"
:id="id"
:name="name"
:type="type"
:value="refDataValue" />
</template>
<template v-else-if="dropDownBind">
<div :class="divClass">
<b-form-select class="attachedSelect"
:id="id"
:aria-label="label"
:aria-required="required"
:data-vv-as="label"
:data-vv-name="label"
:data-vv-scope="scope"
:class="{ 'is-invalid': wDropDown.errors.length > 0 }"
:disabled="disabled || arcDisabledObj"
:label="label"
:multiple="multiple"
:name="name"
:options="options"
:select-size="selectSize"
:text-field="selectText"
v-model="computedVal"
:value-field="selectValue"
#input="onInput">
<template slot="first" v-if="!(multiple) && displayFirstSlot">
<option v-if="customFirstSlotValue !== null"
:value="customFirstSlotValue">
{{placeholderText}}
</option>
<option v-else-if="computedVal !==null && computedVal !== undefined && computedVal.length ===0"
computedVal>
{{placeholderText}}
</option>
<option v-else :value="null">{{placeholderText}}</option>
</template>
</b-form-select>
</div>
</template>
<template v-else>
<div :class="divClass">
<b-form-select class="form-control"
:id="id"
:aria-label="label"
:aria-required="required"
:data-vv-as="label"
:data-vv-name="label"
:data-vv-scope="scope"
:class="{ 'is-invalid': wDropDown.errors.length > 0 }"
:disabled="disabled || arcDisabledObj"
:label="label"
:multiple="multiple"
:name="name"
:options="options"
v-model="computedVal"
:select-size="selectSize"
:text-field="selectText"
:value-field="selectValue"
#input="onInput">
<template slot="first" v-if="!(multiple) && displayFirstSlot">
<option v-if="customFirstSlotValue !== null"
:value="customFirstSlotValue">
{{placeholderText}}
</option>
<option v-else-if="computedVal !==null && computedVal !== undefined && computedVal.length ===0"
computedVal>
{{placeholderText}}
</option>
<option v-else :value="null">{{placeholderText}}</option>
</template>
</b-form-select>
</div>
</template>
<b-form-text v-if="helpText" :id="groupId('hlp', id)">{{helpText}}</b-form-text>
<div class="invalid-feedback" v-if="wDropDown.errors.length > 0">{{ Message }}</div>
<!-- {{ isRequired && (!plaintext && !pagePlaintext) }} {{ isRequired }} {{ plaintext}} {{ overridePageMode }} -->
</wFormGroup>
</ValidationProvider>
</template>
<script>
import uuid from "uuid/v1";
import { groupId } from "#/helpers";
import { classObject } from "#/computed";
import { pagePlaintext } from "#/mixins";
/*
[DEPRECATED]: Left in to support Organization page. Do not use otherwise.
This should be removed in the future.
*/
import { arcInputStateMixin } from "#/components/mixins/UI/inputStateMixin";
export default {
data () {
return {
scope: uuid(),
Message: 'This field is required.',
};
},
methods: {
groupId,
onInput (value) {
this.$emit("input", value);
},
getSelectedDataValue (options, keyValue, keyField, valueField) {
let result = null;
let response = null;
console.log(options);
console.log(keyValue);
console.log(keyField);
console.log(valueField);
console.log(keyValue !== undefined && keyValue !== null);
if(keyValue !== undefined && keyValue !== null) {
response = options.filter(option => option[keyField].toString() === keyValue.toString());
}
console.log('wDropDown', this.id);
console.log(response);
if (this.isNotNullOrUndefined(response)) {
result = response[0][valueField] || null;
}
return result !== null ? result : this.readOnlyValue;
},
},
mixins: [arcInputStateMixin, pagePlaintext],
model: {
event: "input",
prop: "value",
},
name: "wDropDown",
props: {
isRequired: Boolean,
dropDownBind: {
type: Boolean,
default: false,
},
disabled: {
type: Boolean,
},
displayonly: {
type: String,
},
helpText: {
type: String,
},
id: {
required: true,
type: String,
},
inputState: {
type: String,
},
label: {
required: true,
type: String,
},
labelFor: {
type: String,
},
labelSrOnly: {
type: Boolean,
},
maxlength: {
type: String,
},
multiple: {
type: [String, Boolean],
default: false,
},
name: {
type: String,
},
options: {
default () {
return [];
},
type: [Array, String],
},
placeholderText: {
type: String,
default: "- Select One -",
},
plaintext: {
type: Boolean,
},
required: {
type: Boolean,
},
selectSize: {
type: String,
},
selectText: {
type: String,
default: "text",
},
selectValue: {
type: String,
default: "value",
},
type: {
type: String,
},
value: {
type: [Number, String, Array],
default: null,
},
validation: {
type: String,
},
customFirstSlotValue: {
type: [String, Number],
default: null,
},
displayFirstSlot: {
type: [String, Boolean],
default: true,
},
lookUpTableName: {
type: String,
},
overridePageMode: {
type: Boolean,
default: false,
},
readOnlyValue: {
type: String,
},
},
computed: {
rules () {
return (this.isRequired && (!this.plaintext && !this.pagePlaintext) ) ? "required" : "";
},
computedVal: {
get () {
return this.value;
},
set (val) {
return val;
},
},
classObject,
refDataValue () {
return this.getSelectedDataValue(
this.options,
this.computedVal,
this.selectValue,
this.selectText,
);
},
divClass () {
return this.multiple
? "multiSelect"
: (this.disabled || this.arcDisabledObj) === true
? "disable"
: "autofill";
},
},
beforeDestroy () {
//this.$store.commit("Common/SET_ADDRESS_MIXIN_COUNT", 0);
},
};
</script>
The custom component has selectValue and selectText props, which allows setting the b-form-select's value-field and text-field, respectively. You could set those to the desired values without having to remap your data:
<WDropDown :options="dropdownCommissionerValues"
selectText="CommissionerName"
selectValue="CommissionerId"
/>
demo
While not familiar with boostrapVue you could add keys (text and value) either after api call or from the component and using a computed.
Something like:
this.dropdownCommissionerValues = response.data.Table.map(option=>{
option.text=option.commissionerName
option.value=option.commissionerValue
delete option.commissionerName // optional .... clean up the object
delete option.commissionerValue // optional .... clean up the object
return option
})

Meteor app not inserting elements into collection

I am learning Meteor JS and followed a tutorial to build a menu builder shopping list. I am trying to add some features to it. I added one feature successfully, but now I am trying to create an organization feature where users can join an organization and see all shopping lists related to that organization. The first step is to allow for adding an organization by users.
The form appears, and I was able to insert in to the database from the console, but when I use autoform the objects are not being inserted into the database.
I recently upgraded from Meteor 1.3 to 1.4. I don't believe that is an issue since all of the other forms on the app are inserting properly still.
I have a feeling it has something to do with subscribe/publish, but I am not sure what I am doing wrong.
HTML- neworganization.html
<template name='NewOrganization'>
<div class='new-organization-container'>
<i class='fa fa-close'></i>
{{#autoForm collection='Organizations' id='insertOrganizationForm' type='insert'}}
<div class='form-group'>
{{> afQuickField name='organization'}}
</div>
<div class='form-group'>
{{> afQuickField name='members'}}
</div>
<button type="submit" class="btn btn-primary">Add</button>
{{/autoForm}}
</div>
</template>
organizations.html
<template name='Organizations'>
<h3>Your Organizations</h3>
{{#if $.Session.get 'newOrganization'}}
{{> NewOrganization }}
{{else}}
<button class='btn btn-organization btn-primary'>Add an Organization</button>
<button class='btn btn-join'>Join an Organization</button>
<button class='btn btn-deny'>Leave an Organization</button>
{{/if}}
<section class='organization-list'>
{{#if Template.subscriptionsReady}}
{{#each organizationList}}
{{> OrganizationItem}}
{{/each}}
{{else}}
<p>Loading...</p>
{{/if}}
JS- organizations.js
Template.Organizations.onCreated(function() {
this.autorun(() => {
this.subscribe('organizations');
});
});
Template.Organizations.helpers({
organizations() {
return Organizations.find({});
}
});
Template.Organizations.events({
'click .btn-organization': () => {
Session.set('newOrganization', true);
}
});
Template.NewOrganization.helpers({
organizationList: () => {
var organizationItems = Organizations.find({});
return organizationItems;
}
});
newOrganization.js
if (Meteor.isClient) {
Meteor.subscribe('organizations');
}
Template.NewOrganization.events ({
'click .fa-close': function () {
Session.set('newOrganization', false);
}
});
collections/organizations.js
import SimpleSchema from 'simpl-schema';
SimpleSchema.extendOptions(['autoform']);
Organizations = new Mongo.Collection('organizations');
Organizations.allow({
insert: function(userId){
return !!userId;
},
update: function(userId, doc){
return !!userId;
}
});
OrganizationSchema = new SimpleSchema ({
organization: {
label: "Organization Name",
type: String
},
id: {
label: "ID",
type: String,
autoform: {
type: "hidden"
}
},
members: {
type: Array
},
"members.$": Object,
"members.$.name": String,
"members.$.role": String,
inOrganization: {
type: Boolean,
defaultValue: true,
autoform: {
type: 'hidden'
}
},
createdAt: {
type: Date,
label: "CreatedAt",
autoform: {
type: "hidden"
},
autoValue: function() {
return new Date();
}
}
});
Meteor.methods({
deleteOrganizations: function(id) {
Organizations.remove(id);
}
});
Organizations.attachSchema(OrganizationSchema);
The problem is in the way the Schema was designed. I had inserted an id into the schema. My reasoning was that I wanted to have a way to add and remove members from an organization. What I did not take into account was that Mongo autogenerates an id for database object and by designing my schema in this way, I was creating a conflict. I removed the id from my schema and removed the problem.
Here is the new collections/organizations.js file:
import SimpleSchema from 'simpl-schema';
SimpleSchema.extendOptions(['autoform']);
Organizations = new Mongo.Collection('organizations');
Organizations.allow({
insert: function(userId){
return !!userId;
},
update: function(userId, doc){
return !!userId;
}
});
OrganizationSchema = new SimpleSchema ({
organization: {
label: "Organization Name",
type: String
},
members: {
type: Array
},
"members.$": Object,
"members.$.name": String,
"members.$.role": String,
inOrganization: {
type: Boolean,
defaultValue: true,
autoform: {
type: 'hidden'
}
},
createdAt: {
type: Date,
label: "CreatedAt",
autoform: {
type: "hidden"
},
autoValue: function() {
return new Date();
}
}
});
Meteor.methods({
deleteOrganizations: function(id) {
Organizations.remove(id);
}
});
SimpleSchema.debug = true;
Organizations.attachSchema(OrganizationSchema);

How to Get Params from Http Post and Insert

I am trying to capture user entered credentials and use them as a parameter to query a database. Unfortunately, I am a little lost on how to code that process. I am using angular,express, node, jQuery, and html. I am not very experienced with angular, node, and jQuery, so forgive me if this is something very simple; I am here to learn.
Here is the html where the forms live:
<!DOCTYPE html >
<html ng-app="token">
<%include header%>
<%include navbar%>
<div ng-controller="TokenCtrl">
<form ng-submit="submitLogin(loginForm)" role="form" ng-init="loginForm = {}">
<div class="form-group">
<label>email</label>
<input type="email" name="email" ng-model="loginForm.email" required="required" class="form-control"/>
</div>
<div class="form-group">
<label>password</label>
<input type="password" name="password" ng-model="loginForm.password" required="required" class="form-control"/>
</div>
<button class="btn btn-primary btn-lg" ng-click="handleLoginBtnClick()">Sign in</button>
</form>
</div>
</body>
Here is the JS for the TokenCtrl and token module, which is a derivative of ng-token-auth:
var a = angular.module('token', ['ng-token-auth']);
a.config(function($authProvider) {
// the following shows the default values. values passed to this method
// will extend the defaults using angular.extend
$authProvider.configure({
apiUrl: '/users',
tokenValidationPath: '/auth/validate_token',
signOutUrl: '/auth/sign_out',
emailRegistrationPath: '/auth',
accountUpdatePath: '/auth',
accountDeletePath: '/auth',
confirmationSuccessUrl: window.location.href,
passwordResetPath: '/auth/password',
passwordUpdatePath: '/auth/password',
passwordResetSuccessUrl: window.location.href,
emailSignInPath: '/auth/sign_in/:email/:password',
storage: 'cookies',
forceValidateToken: false,
validateOnPageLoad: true,
proxyIf: function() { return false; },
proxyUrl: '/proxy',
omniauthWindowType: 'sameWindow',
tokenFormat: {
"access-token": "{{ token }}",
"token-type": "Bearer",
"client": "{{ clientId }}",
"expiry": "{{ expiry }}",
"uid": "{{ uid }}"
},
cookieOps: {
path: "/",
expires: 9999,
expirationUnit: 'days',
secure: false,
domain: 'domain.com'
},
createPopup: function(url) {
return window.open(url, '_blank', 'closebuttoncaption=Cancel');
},
parseExpiry: function(headers) {
// convert from UTC ruby (seconds) to UTC js (milliseconds)
return (parseInt(headers['expiry']) * 1000) || null;
},
handleLoginResponse: function(response) {
return response.data;
},
handleAccountUpdateResponse: function(response) {
return response.data;
},
handleTokenValidationResponse: function(response) {
return response.data;
}
});
});
a.controller('TokenCtrl', function($scope, $auth) {
$scope.handleRegBtnClick = function() {
$auth.submitRegistration($scope.registrationForm)
.then(function(resp) {
// handle success response
})
.catch(function(resp) {
// handle error response
});
};
$scope.handlePwdResetBtnClick = function() {
$auth.requestPasswordReset($scope.pwdResetForm)
.then(function(resp) {
// handle success response
})
.catch(function(resp) {
// handle error response
});
};
$scope.handleLoginBtnClick = function() {
$auth.submitLogin($scope.loginForm)
.then(function(resp) {
// handle success response
})
.catch(function(resp) {
// handle error response
});
};
$scope.handleSignOutBtnClick = function() {
$auth.signOut()
.then(function(resp) {
// handle success response
})
.catch(function(resp) {
// handle error response
});
};
});
On the run of this function, it leads to this url:
'/auth/sign_in/:email/:password'
Using Express, I route this url to another function. Here is the route code:
app.post('/users/auth/sign_in/:email/:password', routes.verifyusers);
Which leads to,
exports.verifyusers= function(req, res) {
models.user.find({
where: {
email: req.params.email,
password: req.params.password
}
}).then(function(user) {
if(user) {
console.log("alright !")
};
});
};
When the code runs, this is what I get in the console:
Executing (default): SELECT "id", "username", "email", "password", "createdAt", "updatedAt" FROM "users" AS "user" WHERE "user"."email" = ':email' AND "user"."password" = ':password' LIMIT 1;
:email
:password
This is result is irrespective to the form data.
I think the problem is coming from emailSignInPath: '/auth/sign_in/:email/:password',
You should try with
// config
emailSignInPath: '/auth/sign_in'
// route declaration
app.post('/users/auth/sign_in', routes.verifyusers);
// route action
exports.verifyusers = function(req, res) {
models.user.find({
where: {
email: req.body.email,
password: req.body.password
}
}).then(function(user) {
if(user) {
console.log("alright !")
};
});
};
ps: don't forget to declare a body parser in your app app.use(express.bodyParser())

Categories

Resources