Using Ionic2 and Angular2, I want to show an alert box, inside which a text along with checkbox - to ask for user if he/she agree to the statement.
//Prompt an alert, to ask user to verify there email address.
let alert = Alert.create({
subTitle: 'Email not verified!',
message: 'Please check your email for verification link.',
inputs: [
{
name: 'getLink',
label: 'Get verification link again ?',
type: "checkbox",
value: "true",
checked: false
}
],
buttons: [
{
text: 'Ok',
handler: data => {
console.log(data);
if(data.length > 0) {
//console.log('Get me link');
//we are calling this method to sent a link to user over mail - to verify their email address.
user.sendEmailVerification();
this.nav.rootNav.setRoot(HomePage);
return true;
} else {
//console.log('Link not required!');
this.nav.rootNav.setRoot(HomePage);
return true;
}
}
}
]
});
this.nav.present(alert);
Related
I want to add an avatar in the user registration, but I don't know how, Please can someone share with me a full example (form, JS front, and JS backend). I'm using SailsJS 1.0 (the stable version) with VueJs.
Thanks in advance .
I figured it out. Watch these platzi tutorials:
https://courses.platzi.com/classes/1273-sails-js/10757-uploading-backend-file/
https://courses.platzi.com/classes/1273-sails-js/10758-uploading-frontend-files/
https://courses.platzi.com/classes/1273-sails-js/10759-downloading-files/
Here is what the videos tell you to do:
npm i sails-hook-uploads.
In api/controllers/entrance/signup.js
Above inputs key add a new key/value of files: ['avatar'],
In the inputs add:
avatar: {
type: 'ref',
required: true
}
In the body of the fn find var newUserRecord and above this add (even if avatar is not required, make sure to do this line, otherwise you will have a "timeout of unconsuemd file stream":
const avatarInfo = await sails.uploadOne(inputs.avatar);
Then in the first argument object of var newUserRecord = await User.create(_.extend({ add:
avatarFd: avatarInfo.fd,
avatarMime: avatarInfo.type
In api/models/User.js, add these attributes to your User model:
avatarFd: {
type: 'string',
required: false,
description: 'will either have "text" or "avatarFd"'
},
avatarMime: {
type: 'string',
required: false,
description: 'required if "avatarFd" provided'
},
Then create a download endpoint, here is how the action would look for it:
const user = await User.findOne(id);
this.res.type(paste.photoMime);
const avatarStream = await sails.startDownload(paste.photoFd);
return exits.success(avatarStream);
Add to the routes a route for this download avatar endpoint.
Then you can display this avatar by pointing the <img src=""> the source in here to this download endpoint.
------APPENDIX-----
----signup.js-----
module.exports = {
friendlyName: 'Signup',
description: 'Sign up for a new user account.',
extendedDescription:
`This creates a new user record in the database, signs in the requesting user agent
by modifying its [session](https://sailsjs.com/documentation/concepts/sessions), and
(if emailing with Mailgun is enabled) sends an account verification email.
If a verification email is sent, the new user's account is put in an "unconfirmed" state
until they confirm they are using a legitimate email address (by clicking the link in
the account verification message.)`,
files: ['avatar'],
inputs: {
emailAddress: {
required: true,
type: 'string',
isEmail: true,
description: 'The email address for the new account, e.g. m#example.com.',
extendedDescription: 'Must be a valid email address.',
},
password: {
required: true,
type: 'string',
maxLength: 200,
example: 'passwordlol',
description: 'The unencrypted password to use for the new account.'
},
fullName: {
required: true,
type: 'string',
example: 'Frida Kahlo de Rivera',
description: 'The user\'s full name.',
},
avatar: {
}
},
exits: {
success: {
description: 'New user account was created successfully.'
},
invalid: {
responseType: 'badRequest',
description: 'The provided fullName, password and/or email address are invalid.',
extendedDescription: 'If this request was sent from a graphical user interface, the request '+
'parameters should have been validated/coerced _before_ they were sent.'
},
emailAlreadyInUse: {
statusCode: 409,
description: 'The provided email address is already in use.',
},
},
fn: async function (inputs) {
var newEmailAddress = inputs.emailAddress.toLowerCase();
// must do this even if inputs.avatar is not required
const avatarInfo = await sails.uploadOne(inputs.avatar);
// Build up data for the new user record and save it to the database.
// (Also use `fetch` to retrieve the new ID so that we can use it below.)
var newUserRecord = await User.create(_.extend({
emailAddress: newEmailAddress,
password: await sails.helpers.passwords.hashPassword(inputs.password),
fullName: inputs.fullName,
tosAcceptedByIp: this.req.ip,
avatarFd: avatarInfo.fd,
avatarMime: avatarInfo.type
}, sails.config.custom.verifyEmailAddresses? {
emailProofToken: await sails.helpers.strings.random('url-friendly'),
emailProofTokenExpiresAt: Date.now() + sails.config.custom.emailProofTokenTTL,
emailStatus: 'unconfirmed'
}:{}))
.intercept('E_UNIQUE', 'emailAlreadyInUse')
.intercept({name: 'UsageError'}, 'invalid')
.fetch();
// If billing feaures are enabled, save a new customer entry in the Stripe API.
// Then persist the Stripe customer id in the database.
if (sails.config.custom.enableBillingFeatures) {
let stripeCustomerId = await sails.helpers.stripe.saveBillingInfo.with({
emailAddress: newEmailAddress
}).timeout(5000).retry();
await User.updateOne(newUserRecord.id)
.set({
stripeCustomerId
});
}
// Store the user's new id in their session.
this.req.session.userId = newUserRecord.id;
if (sails.config.custom.verifyEmailAddresses) {
// Send "confirm account" email
await sails.helpers.sendTemplateEmail.with({
to: newEmailAddress,
subject: 'Please confirm your account',
template: 'email-verify-account',
templateData: {
fullName: inputs.fullName,
token: newUserRecord.emailProofToken
}
});
} else {
sails.log.info('Skipping new account email verification... (since `verifyEmailAddresses` is disabled)');
}
// add to pubilc group
const publicGroup = await Group.fetchPublicGroup();
await Group.addMember(publicGroup.id, newUserRecord.id);
}
};
I got AWS SES to work with Parse server using
$ npm install parse-server-amazon-ses-email-adapter --save
After changing server.js and setting verifyUserEmails: true I was able to get the verify user emails sending out and the click seting it to true.
I then added my swift code for reset password and was encouraged that when I
entered an email that wasn't user it knew and returned an error. When I put a valid user in no error, but also no email...
PFUser.requestPasswordResetForEmail(inBackground: userName.text!) { (success: Bool, error: Error?) in
if success {
let alert = UIAlertController(title: "Success", message: "Please check your email and follow the instructions", preferredStyle: UIAlertControllerStyle.alert)
let ok = UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: { (UIAlertAction) in
self.dismiss(animated: true, completion: nil)
})
alert.addAction(ok)
self.present(alert, animated: true, completion: nil)
}
else {
print(error?.localizedDescription ?? "")
}
}
Am I possibly missing something that I need to add in the server.js? I have the html and text template in the proper location just like for the verify user. I scoured the internet thinking maybe there was something like the verifyUserEmails setting but I can't figure out what turns that functionality on. Can anyone help? If I can't get this to work I will have to start all over again with mailgun.
This is my server.js for reference:
var api = new ParseServer({
databaseURI: process.env.MONGODB_URI,
cloud: "./node_modules/parse-server/lib/cloud-code/Parse.Cloud.js",
appId: "c4f3ec***************",
masterKey: process.env.MASTER_KEY,
publicServerURL: process.env.SERVER_URL,
verifyUserEmails: true,
appName: process.env.APPNAME,
emailVerifyTokenValidityDuration: 2 * 60 * 60, // in seconds (2 hours = 7200 seconds)
filesAdapter: {
"module": "#parse/s3-files-adapter",
"options": {
"bucket": process.env.S3_BUCKET,
}
},
emailAdapter: new AWSEmailAdapter({
// The address that your emails come from
fromAddress: process.env.EMAIL_FROM_ADDRESS,
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
region: 'us-east-1',
// The template section
templates: {
passwordResetEmail: {
subject: 'Reset your password',
pathPlainText: resolve(__dirname, './email_templates/password_reset_email.txt'),
pathHtml: resolve(__dirname, './email_templates/password_reset_email.html'),
callback: (user) => {
return {
firstName: user.get('firstName')
}
}
// Now you can use {{firstName}} in your templates
},
verificationEmail: {
subject: 'Confirm your account',
pathPlainText: resolve(__dirname, './templates/verification_email.txt'),
pathHtml: resolve(__dirname, './templates/verification_email.html'),
callback: (user) => {
return {
firstName: user.get('firstName')
}
}
// Now you can use {{firstName}} in your templates
},
}
}),
serverURL: process.env.SERVER_URL
});
Oh my goodness I thought of just deleting this question because the solution was so embarrassing, but decided I would just answer it here in case any one else has a similar question and my code snippet (and mistake) would be instructive.
In the server.js that I included above everything was actually set up properly for the most part. The reason that the verify emails were going out and the reset passwords ones were not was because I changed the path for the email templates and only had the correct one on verify (./templates vs ./email_templates). So in short, I corrected that path, saved the changes to server.js, and then ran pm2 restart 0 to restart the server and voila, passwords are resetting!
I have this code in my application:
$ionicPopup.alert({
title: $scope.header1,
template: 'The was a problem connecting to the server. Please check your internet connection and try again.'
});
ionic.Platform.exitApp()
what I have noticed is that in Android, the application exits quickly without showing the pop up message. What I wanted to do is execute
ionic.Platform.exitApp()
after the user press the 'Ok' button in the pop-up. ls there something like an "onleave" event in ionic Popup?
The best approach may be to define your own 'OK' button as opposed to leveraging the default dismiss one - that way you can invoke ionic.Platform.exitApp() upon the user clicking/tapping your button.
Example:
import { AlertController } from 'ionic-angular';
constructor(private alertCtrl: AlertController) {
}
presentAlert() {
let alert = this.alertCtrl.create({
title: YourCustomHeader,
//subTitle: 'optional text',
message: 'The was a problem connecting to the server. Please check your internet connection and try again.',
buttons: [
{
text: 'OK',
handler: () => {
ionic.Platform.exitApp();
}
}
]
});
alert.present();
}
Reference: https://ionicframework.com/docs/api/components/alert/AlertController/#usage
I am creating an ionic 2 application for android and ios. I have an alert controller that prompts the user for a text input, however when the alert pops up I would like the keyboard to focus on the input, and for the placeholder text to be highlighted. Currently you must tap on the text input for the keyboard to pop up. Is this possible to implement?
here is my alert controller code:
let prompt = this.alertCtrl.create({
title: this.name,
message: this.nameMessage,
inputs: [
{
name: 'name',
placeholder: this.name
},
],
buttons: [
{
text: this.save,
handler: data => {
resolve(data.name);
}
}
],
enableBackdropDismiss: false
});
prompt.present();
This is my solution.
First
inputs: [
{
id: "autofocu",
......
}
],
And then
alert.present()
.then(() => {
document.getElementById('autofocu').focus();
})
.catch()
I am using $ionicAuth service that deals with registration and logging in/out. I followed this tutorial https://docs.ionic.io/services/auth/#emailpassword-authentication and https://docs.ionic.io/setup.html - for setting up ionic cloud and using the services. When I try to register, I get this error - $ionicAuth.signup is not a function.Please help me to fix this.
$scope.register = function(){
$scope.error = '';
$ionicAuth.signup($scope.registerData).then(function() {
// `$ionicUser` is now registered
$ionicAuth.login('basic', $scope.registerData).then(function(){
$state.go('login');
});
}, function(err) {
var error_lookup = {
'required_email': 'Missing email field',
'required_password': 'Missing password field',
'conflict_email': 'A user has already signed up with that email',
'conflict_username': 'A user has already signed up with that username',
'invalid_email': 'The email did not pass validation'
}
$scope.error = error_lookup[err.details[0]];
})
}