Skip to content

Commit

Permalink
Login using email, password
Browse files Browse the repository at this point in the history
- Add login, register endpoints in back-end
- Handle login, register, logout using Satellizer
  • Loading branch information
nguyenkims committed Dec 12, 2015
1 parent 602924e commit a727d62
Show file tree
Hide file tree
Showing 6 changed files with 114 additions and 6 deletions.
63 changes: 62 additions & 1 deletion app.py
@@ -1,8 +1,69 @@
import os
import flask
from flask import Flask
import jwt
from datetime import datetime, timedelta
from flask import Flask, jsonify, request
from flask.ext.sqlalchemy import SQLAlchemy

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite'
app.config['TOKEN_SECRET'] = 'very secret'

db = SQLAlchemy(app)


class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(100), nullable=False)
password = db.Column(db.String(100))

def token(self):
payload = {
'sub': self.id,
'iat': datetime.utcnow(),
'exp': datetime.utcnow() + timedelta(days=14)
}
token = jwt.encode(payload, app.config['TOKEN_SECRET'])
return token.decode('unicode_escape')


if os.path.exists('db.sqlite'):
os.remove('db.sqlite')

db.create_all()


@app.route('/auth/signup', methods=['POST'])
def signup():
data = request.json

email = data["email"]
password = data["password"]

user = User(email=email, password=password)
db.session.add(user)
db.session.commit()

return jsonify(token=user.token())


@app.route('/auth/login', methods=['POST'])
def login():
data = request.json

email = data.get("email")
password = data.get("password")

user = User.query.filter_by(email=email).first()
if not user:
return jsonify(error="No such user"), 404

if user.password == password:
return jsonify(token=user.token()), 200
else:
return jsonify(error="Wrong email or password"), 400


@app.route('/islive')
def islive():
Expand Down
3 changes: 2 additions & 1 deletion static/bower.json
Expand Up @@ -20,6 +20,7 @@
],
"dependencies": {
"angular": "angularjs#~1.4.8",
"angular-ui-router": "~0.2.15"
"angular-ui-router": "~0.2.15",
"satellizer": "~0.13.1"
}
}
2 changes: 2 additions & 0 deletions static/index.html
Expand Up @@ -14,6 +14,8 @@

<script src="bower_components/angular/angular.min.js"></script>
<script src="bower_components/angular-ui-router/release/angular-ui-router.min.js"></script>
<script src="bower_components/satellizer/satellizer.min.js"></script>

<script src="main.js"></script>
</body>
</html>
41 changes: 39 additions & 2 deletions static/main.js
@@ -1,4 +1,4 @@
var app = angular.module('DemoApp', ['ui.router']);
var app = angular.module('DemoApp', ['ui.router', 'satellizer']);

app.config(function ($stateProvider, $urlRouterProvider) {

Expand All @@ -10,12 +10,49 @@ app.config(function ($stateProvider, $urlRouterProvider) {
.state('secret', {
url: '/secret',
templateUrl: 'partials/secret.tpl.html',
controller: 'SecretCtrl'
})
.state('login', {
url: '/login',
templateUrl: 'partials/login.tpl.html'
templateUrl: 'partials/login.tpl.html',
controller: 'LoginSignupCtrl'
});

$urlRouterProvider.otherwise('/home');

});


app.controller('LoginSignupCtrl', function ($scope, $auth, $state) {

$scope.signUp = function () {
$auth
.signup({email: $scope.email, password: $scope.password})
.then(function (response) {
$auth.setToken(response);
$state.go('secret');
})
.catch(function (response) {
console.log("error response", response);
})
};

$scope.login = function () {
$auth
.login({email: $scope.email, password: $scope.password})
.then(function (response) {
$auth.setToken(response);
$state.go('secret');
})
.catch(function (response) {
console.log("error response", response);
})
};
});

app.controller('SecretCtrl', function ($scope, $state, $auth) {
$scope.logout = function () {
$auth.logout();
$state.go("home");
};
});
7 changes: 6 additions & 1 deletion static/partials/login.tpl.html
@@ -1 +1,6 @@
Login
Login

<input type="text" ng-model="email" placeholder="Email">
<input type="password" ng-model="password" placeholder="Password">
<button ng-click="signUp()">Sign up</button>
<button ng-click="login()">Login</button>
4 changes: 3 additions & 1 deletion static/partials/secret.tpl.html
@@ -1 +1,3 @@
Secret
Secret

<button ng-click="logout()">Log out</button>

0 comments on commit a727d62

Please sign in to comment.