Skip to content

Commit

Permalink
简单注册登录功能
Browse files Browse the repository at this point in the history
  • Loading branch information
mailgyc-163 committed Jul 9, 2017
1 parent 364da08 commit 0ad0d0d
Show file tree
Hide file tree
Showing 13 changed files with 166 additions and 188 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

运行:

pip3 install tornado bcrypt pymysql
pip3 install tornado bcrypt pymysql msgpack

python3 main.py

Expand Down
4 changes: 2 additions & 2 deletions schema.sql
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ CREATE DATABASE IF NOT EXISTS ddz DEFAULT CHARSET utf8 COLLATE utf8_general_ci;

CREATE TABLE IF NOT EXISTS account (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
email VARCHAR(16) NOT NULL UNIQUE,
email VARCHAR(20) NOT NULL UNIQUE,
username VARCHAR(10) NOT NULL,
password VARCHAR(32) NOT NULL,
password VARCHAR(100) NOT NULL,
coin INT default 4000,
created_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
Expand Down
9 changes: 6 additions & 3 deletions src/core/player.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@


class Player(object):
def __init__(self, uid: int, name: str, socket: WebSocketHandler=None):
def __init__(self, uid: int, name: str, socket: WebSocketHandler = None):
from core.table import Table
self.uid = uid
self.name = name
Expand Down Expand Up @@ -95,8 +95,11 @@ def join_table(self, t):
def leave_table(self):
self.ready = False
if self.table:
self.table.remove(self)
logger.info('Player[%d] leave Table[%d]', self.uid, self.table.uid)
self.table.remove(self)
logger.info('Player[%d] leave Table[%d]', self.uid, self.table.uid)

def __repr(self):
return self.__str__()

def __str__(self):
return self.uid + '-' + self.name
1 change: 1 addition & 0 deletions src/core/robot.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,3 +70,4 @@ def auto_shot_poker(self):
packet = [Pt.REQ_SHOT_POKER, pokers]
# IOLoop.current().add_callback(self.to_server, packet)
IOLoop.current().call_later(2, self.to_server, packet)

9 changes: 6 additions & 3 deletions src/core/room.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ def find_waiting_table(self, uid, default=None):
def first_waiting_table(self):
for _, table in self.waiting_tables.items():
return table
t = Table()
t = Table(self)
self.waiting_tables[t.uid] = t
return t

Expand Down Expand Up @@ -61,12 +61,15 @@ def playing_tables(self):
class RoomManager(object):
__metaclass__ = Singleton

__room_dict = {}
__room_dict = {
1: Room(1, True),
2: Room(2, False),
}

@staticmethod
def find_room(uid, created=False):
room = RoomManager.__room_dict.get(uid)
if not room and created:
room = Room(0)
room = Room(uid)
RoomManager.__room_dict[uid] = room
return room
4 changes: 2 additions & 2 deletions src/core/table.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,11 @@ def ai_join(self, nth=1):
if size == 2 and nth == 1:
IOLoop.current().call_later(1, self.ai_join, nth=2)

p1 = AiPlayer(11, 'AI-1', self.players[0])
p1 = AiPlayer(11, 'IDIOT-I', self.players[0])
p1.to_server([Pt.REQ_JOIN_TABLE, self.uid])

if size == 1:
p2 = AiPlayer(12, 'AI-2', self.players[0])
p2 = AiPlayer(12, 'IDIOT-II', self.players[0])
p2.to_server([Pt.REQ_JOIN_TABLE, self.uid])

def sync_table(self):
Expand Down
34 changes: 34 additions & 0 deletions src/net/base.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
from concurrent.futures import ThreadPoolExecutor

from tornado.escape import json_encode
from tornado.web import RequestHandler

from db import torndb


class BaseHandler(RequestHandler):

@property
def db(self) -> torndb.Connection:
return self.application.db

@property
def executor(self) -> ThreadPoolExecutor:
return self.application.executor

def data_received(self, chunk):
pass

def get_current_user(self):
return self.get_secure_cookie("user")

def set_current_user(self, uid, username):
info = {
'uid': uid,
'username': username,
}
self.set_secure_cookie('user', json_encode(info))

def on_finish(self):
# self.session.flush()
pass
26 changes: 16 additions & 10 deletions src/net/socket.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
import logging

import msgpack
from tornado.escape import json_decode
from tornado.web import authenticated
from tornado.websocket import WebSocketHandler, WebSocketClosedError

from core.player import Player
Expand Down Expand Up @@ -33,6 +35,9 @@ def __init__(self, application, request, **kwargs):
def data_received(self, chunk):
logger.info('socket data_received')

def get_current_user(self):
return json_decode(self.get_secure_cookie("user"))

@property
def uid(self):
return self.player.uid
Expand All @@ -41,9 +46,10 @@ def uid(self):
def room(self):
return self.player.room

@authenticated
def open(self):
self.player = Player(10, 'Jerry', self)
self.player.room = RoomManager.find_room(0, True)
user = self.current_user
self.player = Player(user['uid'], user['username'], self)
logger.info('SOCKET[%s] OPEN', self.player.uid)

def on_message(self, message):
Expand All @@ -57,19 +63,20 @@ def on_message(self, message):
self.write_message(response)

elif code == Pt.REQ_ROOM_LIST:
response = [Pt.RSP_ROOM_LIST]
self.write_message(response)
self.write_message([Pt.RSP_ROOM_LIST])

elif code == Pt.REQ_TABLE_LIST:
response = [Pt.RSP_TABLE_LIST, self.room.tables()]
self.write_message(response)
self.write_message([Pt.RSP_TABLE_LIST, self.room.tables()])

elif code == Pt.REQ_JOIN_ROOM:
self.player.room = RoomManager.find_room(packet[1])
self.write_message([Pt.RSP_JOIN_ROOM])

elif code == Pt.REQ_JOIN_TABLE:
table_id = packet[1]
table = self.find_table(table_id)
if not table:
response = [Pt.RSP_TABLE_LIST, self.room.tables()]
self.write_message(response)
self.write_message([Pt.RSP_TABLE_LIST, self.room.tables()])
logger.info('PLAYER[%d] JOIN FULL TABLE[%d]', self.uid, table.uid)

self.player.join_table(table)
Expand Down Expand Up @@ -125,9 +132,8 @@ def write_message(self, message, binary=False):
return self.ws_connection.write_message(packet, binary=binary)

def on_close(self):
# self.session.get(self.uid).socket = None
logger.info('socket[%s] close', self.player.uid)
if self.player:
logger.info('socket[%s] close', self.player.uid)
self.player.leave_table()

def send_updates(cls, chat):
Expand Down
54 changes: 15 additions & 39 deletions src/net/web.py
Original file line number Diff line number Diff line change
@@ -1,45 +1,21 @@
import json
import subprocess
from concurrent.futures import ThreadPoolExecutor

import bcrypt
import tornado.escape
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from tornado.web import RequestHandler

from db import torndb
from core.player import Player


class BaseHandler(RequestHandler):
@property
def db(self) -> torndb.Connection:
return self.application.db

@property
def executor(self) -> ThreadPoolExecutor:
return self.application.executor

def data_received(self, chunk):
pass

def on_finish(self):
# self.session.flush()
pass
from net.base import BaseHandler


class WebHandler(BaseHandler):
# @tornado.web.authenticated
def get(self):
if not self.get_cookie("_csrf"):
self.set_cookie("_csrf", self.xsrf_token)
self.render('poker.html')
# user = xhtml_escape(self.current_user or '')
user = self.current_user or ''
self.render('poker.html', user=user)


class UpdateHandler(BaseHandler):
# @tornado.web.authenticated
def get(self):
proc = subprocess.run(["git", "pull"], stdout=subprocess.PIPE)
self.head('content-type', 'text/plain; charset=UTF-8')
Expand All @@ -51,8 +27,10 @@ class RegHandler(BaseHandler):
def post(self):
email = self.get_argument('email', self.get_argument('username'))
account = self.db.get('SELECT * FROM account WHERE email="%s"', email)

if account:
raise tornado.web.HTTPError(400, "username already taken")
self.write('1')
return

username = self.get_argument('username')
password = self.get_argument('password')
Expand All @@ -61,28 +39,26 @@ def post(self):
uid = self.db.insert('INSERT INTO account (email, username, password) VALUES ("%s", "%s", "%s")',
email, username, password)

self.set_secure_cookie("uid", str(account.get('id')))
self.write('ok')
self.set_current_user(uid, username)
self.write('0')


class LoginHandler(BaseHandler):

def post(self):
username = self.get_argument('email')
email = self.get_argument('email')
password = self.get_argument("password")
account = self.db.get('SELECT * FROM account WHERE email="%s"', self.get_argument('email'))
account = self.db.get('SELECT * FROM account WHERE email="%s"', email)
password = bcrypt.hashpw(password.encode('utf8'), account.get('password'))

self.head('content-type', 'application/json')
if password == account.get('password'):
self.set_secure_cookie("uid", str(account.get('id')))
self.set_current_user(account.get('id'), account.get('username'))
self.redirect(self.get_argument("next", "/"))


class LoginoutHandler(BaseHandler):
class LogoutHandler(BaseHandler):

def post(self):
uid = self.get_secure_cookie("uid")
self.clear_cookie("uid")
self.session.remove(int(uid))
self.clear_cookie('user')
self.redirect(self.get_argument("next", "/"))
Binary file added src/static/i/btn/register.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading

0 comments on commit 0ad0d0d

Please sign in to comment.