Skip to content

Commit

Permalink
authentication-1
Browse files Browse the repository at this point in the history
  • Loading branch information
sherifrad committed Jun 8, 2018
1 parent 2f23251 commit 2b783f5
Show file tree
Hide file tree
Showing 20 changed files with 215 additions and 33 deletions.
Binary file modified __pycache__/blog.cpython-36.pyc
Binary file not shown.
Binary file modified __pycache__/config.cpython-36.pyc
Binary file not shown.
8 changes: 7 additions & 1 deletion app/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,16 @@
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate


# Flask application instance
app = Flask(__name__)
app.config.from_object(Config)
db = SQLAlchemy(app)
migrate = Migrate(app, db)

# register the Blueprints occur here
from . import auth
app.register_blueprint(auth.bp)

# DataBase instance

from . import models, routes
Binary file modified app/__pycache__/__init__.cpython-36.pyc
Binary file not shown.
Binary file added app/__pycache__/auth.cpython-36.pyc
Binary file not shown.
Binary file modified app/__pycache__/models.cpython-36.pyc
Binary file not shown.
Binary file modified app/__pycache__/routes.cpython-36.pyc
Binary file not shown.
65 changes: 65 additions & 0 deletions app/auth.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
from . import app, db
from .models import User
from flask import render_template, redirect, url_for, request, Blueprint, flash, session
from werkzeug.security import generate_password_hash, check_password_hash

bp = Blueprint('auth', __name__, url_prefix='/auth')


@bp.route('/register', methods=['POST', 'GET'])
def register():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
identical_user = User.query.filter(User.username == username).first()
error = None

if not username:
error = 'Username field is qequired'
elif identical_user is not None:
error = 'This username is already registered'
elif not password:
error = 'password field is required'

if error is not None:
return render_template('auth/register.html', error=error)
else:
new_user = User(username=username, password=generate_password_hash(password))
db.session.add(new_user)
db.session.commit()

return redirect(url_for('auth.login'))
# flash(error)
else:
return render_template('auth/register.html')


@bp.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
user = User.query.filter_by(username=username).first()
all_identical_users = User.query.filter(User.username == username).first()
error = None

if not username:
error = 'USERNAME is required Ya Dog :) '
# To check if the password not correct ???
# elif username not in
elif all_identical_users is None:
error = 'User Not Registered'
elif not check_password_hash(user.password, password):
error = 'Incorrect password Ya Animal :) '

if error is not None:
flash(error)
return render_template('auth/login.html', error=error,
all_identical_users=all_identical_users)
else:
# create new session
session.clear()
session['user-id'] = user.id
return redirect(url_for('index'))

return render_template('auth/login.html')
27 changes: 19 additions & 8 deletions app/models.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,25 @@
from datetime import datetime
from app import db


class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100), nullable=False)
body = db.Column(db.Text, nullable=False)
pub_date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100), nullable=False)
body = db.Column(db.Text, nullable=False)
pub_date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)

def date(self):
return self.pub_date.strftime('%d %B - %H:%M:%S (UTC)')

def __repr__(self):
return '<Post %r>' % self.title


def date(self):
return self.pub_date.strftime('%d %B - %H:%M:%S (UTC)')
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(20), nullable=False, unique=True)
password = db.Column(db.String(50), nullable=False)
time_registered = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)

def __repr__(self):
return '<Post %r>' % self.title
def __repr__(self):
return '{}'.format(self.username)
48 changes: 26 additions & 22 deletions app/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,36 +2,40 @@
from .models import Post
from flask import render_template, redirect, url_for, request


@app.route('/')
def index():
posts = Post.query.all()
posts.sort(key=lambda p: p.pub_date, reverse=True)
return render_template('index.html', posts=posts)
posts = Post.query.all()
posts.sort(key=lambda p: p.pub_date, reverse=True)
return render_template('index.html', posts=posts)


@app.route('/<int:post_id>')
def detail(post_id):
post = Post.query.get(post_id)
return render_template('detail.html', post=post)
post = Post.query.get(post_id)
return render_template('detail.html', post=post)


@app.route('/new', methods=['GET', 'POST'])
def new():
if request.method == 'POST':
title = request.form.get('title')
body = request.form.get('body')
new_post = Post(title=title, body=body)
db.session.add(new_post)
db.session.commit()
return redirect(url_for('index'))
else: # GET
return render_template('new.html')
if request.method == 'POST':
title = request.form.get('title')
body = request.form.get('body')
new_post = Post(title=title, body=body)
db.session.add(new_post)
db.session.commit()
return redirect(url_for('index'))
else: # GET
return render_template('new.html')


@app.route('/edit/<int:post_id>', methods=['GET', 'POST'])
def edit(post_id):
post = Post.query.get(post_id)
if request.method == 'POST':
post.title = request.form.get('title')
post.body = request.form.get('body')
db.session.commit()
return redirect(url_for('detail', post_id=post_id))
else: #GET
return render_template('edit.html', post=post)
post = Post.query.get(post_id)
if request.method == 'POST':
post.title = request.form.get('title')
post.body = request.form.get('body')
db.session.commit()
return redirect(url_for('detail', post_id=post_id))
else: # GET
return render_template('edit.html', post=post)
17 changes: 17 additions & 0 deletions app/templates/auth/login.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{%with messages = get_flashed_messages()%}
{%if messages%}
{%for message in messages%}
<ul>{{message}}</ul>
{%endfor%}
{%endif%}
{%endwith%}
{{all_identical_users}}
<form method="POST">
<label for="username">Username</label>
<input name="username" id="username" required>
<label for="password">Password</label>
<input type="password" name="password" id="password" required>
<input type="submit" name="Login">

</form>

14 changes: 14 additions & 0 deletions app/templates/auth/register.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{%if error%}
{{error}}
{%endif%}

{% block content %}
<form method="POST">
<label for="username">Username</label>
<input name="username" id="username" required>
<label for="password">Password</label>
<input type="password" name="password" id="password">
<input type="submit" name="Login">
</form>
{% endblock %}

Binary file modified blog.db
Binary file not shown.
7 changes: 5 additions & 2 deletions config.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

basedir = os.path.abspath(os.path.dirname(__file__))


class Config:
SQLALCHEMY_DATABASE_URI = 'sqlite:https:///' + os.path.join(basedir, 'blog.db')
SQLALCHEMY_TRACK_MODIFICATIONS = False
SECRET_KEY = 'dev'
DEBUG = True
SQLALCHEMY_DATABASE_URI = 'sqlite:https:///' + os.path.join(basedir, 'blog.db')
SQLALCHEMY_TRACK_MODIFICATIONS = False
Binary file modified migrations/__pycache__/env.cpython-36.pyc
Binary file not shown.
28 changes: 28 additions & 0 deletions migrations/versions/12b611e156b0_modify_method.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
"""modify method
Revision ID: 12b611e156b0
Revises: 37b3916ccd8b
Create Date: 2018-06-09 01:23:29.668766
"""
from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision = '12b611e156b0'
down_revision = '37b3916ccd8b'
branch_labels = None
depends_on = None


def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_unique_constraint(None, 'user', ['username'])
# ### end Alembic commands ###


def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_constraint(None, 'user', type_='unique')
# ### end Alembic commands ###
34 changes: 34 additions & 0 deletions migrations/versions/37b3916ccd8b_users_table.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
"""users table
Revision ID: 37b3916ccd8b
Revises: e58b08b6e626
Create Date: 2018-06-08 18:16:07.112604
"""
from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision = '37b3916ccd8b'
down_revision = 'e58b08b6e626'
branch_labels = None
depends_on = None


def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('user',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('username', sa.String(length=20), nullable=False),
sa.Column('password', sa.String(length=50), nullable=False),
sa.Column('time_registered', sa.DateTime(), nullable=False),
sa.PrimaryKeyConstraint('id')
)
# ### end Alembic commands ###


def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('user')
# ### end Alembic commands ###
Binary file not shown.
Binary file not shown.
Binary file modified migrations/versions/__pycache__/e58b08b6e626_.cpython-36.pyc
Binary file not shown.

0 comments on commit 2b783f5

Please sign in to comment.