init commit.

This commit is contained in:
wangjiacai 2023-03-31 22:11:34 +08:00
commit 10232e73fd
9 changed files with 299 additions and 0 deletions

40
project/__init__.py Normal file
View File

@ -0,0 +1,40 @@
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
# init SQLAlchemy so we can use it later in our models
db = SQLAlchemy()
def create_app():
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret-key-goes-here'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///sqlite.db'
db.init_app(app)
login_manager = LoginManager()
login_manager.login_view = 'auth.login'
login_manager.init_app(app)
from .models import User
@login_manager.user_loader
def load_user(user_id):
# since the user_id is just the primary key of our user table, use it in the query for the user
return User.query.get(int(user_id))
from . import models
with app.app_context():
db.create_all()
# blueprint for auth routes in our app
from .auth import auth as auth_blueprint
app.register_blueprint(auth_blueprint)
# blueprint for non-auth parts of app
from .main import main as main_blueprint
app.register_blueprint(main_blueprint)
return app

77
project/auth.py Normal file
View File

@ -0,0 +1,77 @@
from flask_login import login_user, logout_user
from flask import Blueprint, render_template, redirect, url_for, request, flash
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import login_required, current_user, login_manager
from .models import User
from . import db
auth = Blueprint('auth', __name__)
@auth.route('/login')
def login():
return render_template('login.html')
@auth.route('/login', methods=['POST'])
def login_post():
# login code goes here
email = request.form.get('email')
password = request.form.get('password')
remember = True if request.form.get('remember') else False
user = User.query.filter_by(email=email).first()
# check if the user actually exists
# take the user-supplied password, hash it, and compare it to the hashed password in the database
if not user or not check_password_hash(user.password, password):
flash('Please check your login details and try again.')
# if the user doesn't exist or password is wrong, reload the page
return redirect(url_for('auth.login'))
# if the above check passes, then we know the user has the right credentials
login_user(user, remember=remember)
return redirect(url_for('main.profile'))
@auth.route('/signup')
def signup():
return render_template('signup.html')
@auth.route('/signup', methods=['POST'])
def signup_post():
# code to validate and add user to database goes here
email = request.form.get('email')
name = request.form.get('name')
password = request.form.get('password')
# if this returns a user, then the email already exists in database
user = User.query.filter_by(email=email).first()
if user: # if a user is found, we want to redirect back to signup page so user can try again
flash('此邮箱已注册!')
return redirect(url_for('auth.signup'))
if not (email):
flash('Email missing!')
return redirect(url_for('auth.signup'))
if not (name):
name = email
if not (password):
flash('Password missing!')
return redirect(url_for('auth.signup'))
# create a new user with the form data. Hash the password so the plaintext version isn't saved.
new_user = User(email=email, name=name,
password=generate_password_hash(password, method='sha256'), role='user', isActivated=False)
# add the new user to the database
db.session.add(new_user)
db.session.commit()
return redirect(url_for('auth.login'))
@auth.route('/logout')
def logout():
if current_user.is_authenticated:
logout_user()
return redirect(url_for('main.index'))

21
project/main.py Normal file
View File

@ -0,0 +1,21 @@
from flask import Blueprint, render_template
from flask_login import login_required, current_user, login_manager
from . import db
main = Blueprint('main', __name__)
@main.route('/')
def index():
if current_user.is_authenticated:
name = current_user.name
else:
name = '游客'
return render_template('index.html', username=name, is_authenticated=current_user.is_authenticated)
@main.route('/profile')
@login_required
def profile():
login_manager.login_message = "请先登录"
return render_template('profile.html', username=current_user.name, isActivated=current_user.isActivated)

12
project/models.py Normal file
View File

@ -0,0 +1,12 @@
from flask_login import UserMixin
from . import db
class User(UserMixin, db.Model):
# primary keys are required by SQLAlchemy
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(100), unique=True, nullable=False)
password = db.Column(db.String(100), nullable=False)
name = db.Column(db.String(100), nullable=False)
role = db.Column(db.String(100), nullable=False)
isActivated = db.Column(db.Boolean, nullable=False)

View File

@ -0,0 +1,47 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Flask</title>
<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.2/css/bulma.min.css" />
<script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<nav class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse"
data-target="#account-navbar-collapse">
<span class="sr-only">切换导航</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="{{ url_for('main.index') }}">主页</a>
</div>
<div class="collapse navbar-collapse" style="float: right;" id="account-navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="{{ url_for('main.profile') }}">账户</a></li>
<li><a href="{{ url_for('auth.login') }}">登录</a></li>
<li><a href="{{ url_for('auth.signup') }}">注册</a></li>
<li><a href="{{ url_for('auth.logout') }}">退出</a></li>
</ul>
</div>
</div>
</nav>
<div class="hero-body">
<div class="container has-text-centered">
{% block content %}
{% endblock %}
</div>
</div>
</body>
</html>

View File

@ -0,0 +1,13 @@
{% extends "base.html" %}
{% block content %}
<h2 class="subtitle">
你好, {{ username }}。
{% if not is_authenticated %}
<br> <br>
<a href="{{ url_for('auth.login') }}"><button type="button" class="btn btn-primary">登录</button></a>
<a href="{{ url_for('auth.signup') }}"><button type="button" class="btn btn-default">注册</button></a>
{% endif %}
</h2>
{% endblock %}

View File

@ -0,0 +1,36 @@
{% extends "base.html" %}
{% block content %}
<div class="column is-4 is-offset-4">
<h3 class="title">登录</h3>
<div class="box">
{% with messages = get_flashed_messages() %}
{% if messages %}
<div class="notification is-danger">
{{ messages[0] }}
</div>
{% endif %}
{% endwith %}
<form method="POST" action="/login">
<div class="field">
<div class="control">
<input class="input is-large" type="email" name="email" placeholder="Your Email" autofocus="">
</div>
</div>
<div class="field">
<div class="control">
<input class="input is-large" type="password" name="password" placeholder="Your Password">
</div>
</div>
<div class="field">
<label class="checkbox">
<input type="checkbox" name="remember">
记住我
</label>
</div>
<button class="button is-block is-info is-large is-fullwidth">登录</button>
</form>
</div>
</div>
{% endblock %}

View File

@ -0,0 +1,12 @@
{% extends "base.html" %}
{% block content %}
<h1 class="title">
欢迎回来, {{ username }}!
</h1>
{% if isActivated %}
开始聊天吧
{% else %}
您的账号暂未激活,请等待管理员激活此账号。
{% endif %}
{% endblock %}

View File

@ -0,0 +1,41 @@
{% extends "base.html" %}
{% block content %}
<div class="column is-4 is-offset-4">
<h3 class="title">注册</h3>
<div class="box">
{% with messages = get_flashed_messages() %}
{% if messages %}
<div class="notification is-danger">
{{ messages[0] }}
{% if messages[0] == '此邮箱已注册!' %}
<a href="{{ url_for('auth.login') }}">点此登录</a>.
{% endif %}
</div>
{% endif %}
{% endwith %}
<form method="POST" action="/signup">
<div class="field">
<div class="control">
<input class="input is-large" type="email" name="email" placeholder="邮箱" autofocus=""
required="required">
</div>
</div>
<div class="field">
<div class="control">
<input class="input is-large" type="password" name="password" placeholder="密码" required="required">
</div>
</div>
<div class="field">
<div class="control">
<input class="input is-large" type="text" name="name" placeholder="昵称(可选)" autofocus="">
</div>
</div>
<button class="button is-block is-info is-large is-fullwidth">Sign Up</button>
</form>
</div>
</div>
{% endblock %}