Skip to content

Instantly share code, notes, and snippets.

@singledigit

singledigit/Activate

Last active Jul 1, 2016
Embed
What would you like to do?
Code examples for Serverless Architecture Demo part 3
activate(){
return this.auth.getSession();
}
import {inject} from 'aurelia-framework';
import {Session} from './session';
@inject(Session)
export class Auth {
// App specific
userPoolId = 'us-east-1_fgCWraBkF';
appClientId = '57lq262n28o7ddt8i36jcjj7qd';
identityPoolId = 'us-east-1:35b6094e-ff5b-44a5-ac52-e879ae263c91';
region = 'us-east-1';
constructor(session) {
this.session = session;
// Required as mock credentials
AWSCognito.config.update({accessKeyId: 'mock', secretAccessKey: 'mock'});
// pool data
this.poolData = {
UserPoolId: this.userPoolId,
ClientId: this.appClientId
};
// create user pool
this.userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(this.poolData);
// construct login id
this.loginId = `cognito-idp.${this.region}.amazonaws.com/${this.userPoolId}`;
}
registerUser(user) {
let attributes = [];
let emailData = {
Name: 'email',
Value: user.email
};
let nameData = {
Name: 'name',
Value: user.name
};
attributes.push(new AWSCognito.CognitoIdentityServiceProvider.CognitoUserAttribute(emailData));
attributes.push(new AWSCognito.CognitoIdentityServiceProvider.CognitoUserAttribute(nameData));
this.userPool.signUp(user.username, user.password, attributes, null, (err, result) => {
if (err) {
console.log(err);
return;
}
this.session.registered = true;
});
}
confirmUser(username, code) {
let userData = {
Username: username,
Pool: this.userPool
};
let cognitoUser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData);
cognitoUser.confirmRegistration(code, true, (err, result) => {
if (err) {
console.log(err);
return;
}
this.session.confirmed = true;
});
}
loginUser(username, password) {
let authData = {
Username: username,
Password: password
};
let authDetails = new AWSCognito.CognitoIdentityServiceProvider.AuthenticationDetails(authData);
let userData = {
Username: username,
Pool: this.userPool
};
let cognitoUser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData);
cognitoUser.authenticateUser(authDetails, {
onSuccess: (result) => {
this.setCredentials(result.getIdToken().getJwtToken());
this.session.user = cognitoUser;
},
onFailure: (err) => {
console.log(err);
}
});
}
getSession() {
let cognitoUser = this.userPool.getCurrentUser();
if (cognitoUser) {
return new Promise((resolve, reject) => {
cognitoUser.getSession((err, result) => {
if (err) {
this.logoutUser();
reject('User not logged in');
}
else {
this.setCredentials(result.getIdToken().getJwtToken());
this.session.user = cognitoUser;
resolve(true);
}
})
});
}
}
logoutUser() {
let cognitoUser = this.userPool.getCurrentUser();
this.session.user = null;
if (cognitoUser != null) cognitoUser.signOut();
}
getUserAttributes() {
return new Promise((resolve, reject) => {
this.session.user.getUserAttributes((err, result) => {
if (err) reject(err);
else resolve(result);
})
})
}
setCredentials(token) {
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: this.identityPoolId,
Logins: {}
});
AWS.config.credentials.params.Logins[this.loginId] = token;
}
}
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"mobileanalytics:PutEvents",
"cognito-sync:*",
"cognito-identity:*"
],
"Resource": [
"*"
]
},
{
"Effect": "Allow",
"Action": [
"lambda:InvokeFunction"
],
"Resource": [
"serveless-pdf arn here",
"serverless-query arn here"
]
}
]
}
import {inject} from 'aurelia-framework';
import {Session} from '../system/session';
import showdown from 'showdown';
@inject(Session)
export class Index {
markdown = '#hello, markdown!';
translation = '';
files = [];
constructor(session) {
this.converter = new showdown.Converter();
this.session = session;
this.lambda = new AWS.Lambda()
}
translate() {
this.translation = this.converter.makeHtml(this.markdown);
}
createPDF() {
this.lambda.invoke({
FunctionName: 'serverless-pdf',
Payload: JSON.stringify({html: this.translation})
}, (err, data) => {
if (err) console.log(err);
else {
console.log(data.Payload);
this.files.push(JSON.parse(data.Payload));
}
})
}
activate() {
this.translate();
}
}
getSession() {
let cognitoUser = this.userPool.getCurrentUser();
if (cognitoUser) {
return new Promise((resolve, reject) => {
cognitoUser.getSession((err, result) => {
if (err) {
this.logoutUser();
reject('User not logged in');
}
else {
this.setCredentials(result.getIdToken().getJwtToken());
this.session.user = cognitoUser;
resolve(true);
}
})
});
}
}
<script>
AWS.config.region = 'us-east-1'; // Region
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: 'us-east-1:35b6094e-ff5b-44a5-ac52-e879ae263c91' // your identity pool id here
});
AWSCognito.config.region = 'us-east-1';
AWSCognito.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: 'us-east-1:35b6094e-ff5b-44a5-ac52-e879ae263c91' // your identity pool id here
});
</script>
loginUser(username, password) {
let authData = {
Username: username,
Password: password
};
let authDetails = new AWSCognito.CognitoIdentityServiceProvider.AuthenticationDetails(authData);
let userData = {
Username: username,
Pool: this.userPool
};
let cognitoUser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData);
cognitoUser.authenticateUser(authDetails, {
onSuccess: (result) => {
this.setCredentials(result.getIdToken().getJwtToken());
this.session.user = cognitoUser;
},
onFailure: (err) => {
console.log(err);
}
});
}
import {inject} from 'aurelia-framework';
import {Session} from './session';
@inject(Session)
export class Auth {
// App specific
userPoolId = 'us-east-1_fgCWraBkF';
appClientId = '57lq262n28o7ddt8i36jcjj7qd';
identityPoolId = 'us-east-1:35b6094e-ff5b-44a5-ac52-e879ae263c91';
region = 'us-east-1';
constructor(session) {
this.session = session;
// Required as mock credentials
AWSCognito.config.update({accessKeyId: 'mock', secretAccessKey: 'mock'});
// pool data
this.poolData = {
UserPoolId: this.userPoolId,
ClientId: this.appClientId
};
// create user pool
this.userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(this.poolData);
// construct login id
this.loginId = `cognito-idp.${this.region}.amazonaws.com/${this.userPoolId}`;
}
'use strict';
let AWS = require('aws-sdk');
let dynamo = new AWS.DynamoDB();
exports.handler = (event, context, callback) => {
const document = event.Records[0].s3;
const parts = document.object.key.split('/');
const documentPayload = {
TableName: 'serverless_docs',
Item: {
id: {S: parts[1]},
document: {S: parts[2]}
}
};
dynamo.putItem(documentPayload, (err, data) => {
if (err) callback(new Error(err));
else callback(null, data);
});
};
'use strict';
let AWS = require('aws-sdk');
let dynamodb = new AWS.DynamoDB();
let dc = new AWS.DynamoDB.DocumentClient({ service: dynamodb });
exports.handler = (event, context, callback) => {
const docPayload = {
TableName: 'serverless_docs',
KeyConditionExpression: "id = :id",
ExpressionAttributeValues: {
":id": encodeURIComponent(context.identity.cognitoIdentityId)
}
};
dc.query(docPayload, (err, data) => {
if (err) callback(new Error(err));
else callback(null, data);
});
};
setCredentials(token) {
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: this.identityPoolId,
Logins: {}
});
AWS.config.credentials.params.Logins[this.loginId] = token;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.