Esempio n. 1
0
class AccessLogFilter(Filter):
    def __init__(self):
        pass

    def before_request(self, ctx, request):
        request.start = datetime.datetime.now()
        return request

    def after_request(self, ctx, request, response):
        now = datetime.datetime.now()
        time = (now - request.start).total_seconds()
        logging.info(str(time))
        return response

router = Router(filters=[AccessLogFilter()])


@router.before_request
def audit(ctx, request):
    logging.info(request.path)
    return request


def authenticated(fn):
    @wraps(fn)
    def wrap(ctx, request):
        token = request.headers.get('X-Authorization-Token')
        if token is None:
            raise HTTPUnauthorized()
        try:
Esempio n. 2
0
                to['done'] = True

    def reopen(self, id):
        for to in self.todo:
            if to['id'] == id:
                to['done'] = False
                break

    def list(self, filter='todo'):
        if filter == 'todo':
            return [t for t in self.todo if not t['done']]
        if filter == 'all':
            return [t for t in self.todo]


router = Router('/api/todo')


@router.route('', methods=['POST'])
def add(ctx, request):
    content = request.json()['content']
    id = ctx.storage.add(content)
    return jsonify(code=200, id=id)


@router.route('/{filter:str}', methods=['GET'])
def list(ctx, request):
    filter = request.args.get('filter')
    todo = ctx.storage.list(filter)
    return jsonify(code=200, todo=todo)
Esempio n. 3
0
import logging
from m import Router
from m.utils import jsonify
from m.security import Require
from webob import exc
from ..models import db, Catalog, Post


router = Router('/api/catalog')


@router.post('')
@Require()
def add(ctx, request):
    try:
        name = request.json()['name']
    except Exception as e:
        raise exc.HTTPBadRequest(e)
    user = request.principal
    catalog = Catalog.query.filter(Catalog.user == user.id)\
        .filter(Catalog.name == name).first()
    if catalog is None:
        catalog = Catalog(name=name, user=user.id)
        db.session.add(catalog)
        try:
            db.session.commit()
        except Exception as e:
            logging.error(e)
            db.session.rollback()
            raise exc.HTTPInternalServerError(e)
    return jsonify(code=200, catalog=catalog.dictify())
Esempio n. 4
0
import re
import datetime
import logging
from m import Router
from m.security import Require
from m.utils import jsonify
from webob import exc
from ..models import db, Post, PostContent, Catalog, Like, Favorite

router = Router('/api/post')

img_re = re.compile(r'''!\[(.*)\]\((.*)\)''')


def update_post(request, status=0):
    try:
        payload = request.json()
        post_id = payload['post']
        content = payload.get('content')
        title = payload.get('title')
        catalog_id = payload.get('catalog')
    except Exception as e:
        raise exc.HTTPBadRequest(e)
    post = Post.query.filter(Post.id == post_id).first_or_404()
    if post.author_id != request.principal.id:
        raise exc.HTTPForbidden('it is not your post')
    if post.status != 0:
        raise exc.HTTPBadRequest('post is published or deleted')
    if title is not None:
        post.title = title
    if catalog_id is not None:
Esempio n. 5
0
            decoded = jwt.decode(token.encode(), KEY, ['HS512'])
            user = decoded.get('user')
            if user is None:
                raise HTTPUnauthorized()
            self.__principal = Principal('comyn', ['admin'])
        except Exception as e:
            logging.error(e)
            raise HTTPUnauthorized()

    @property
    def principal(self):
        return self.__principal


router = Router(filters=[
    AccessLogFilter(),
    AuthenticationFilter(JWTAuthenticationProvider, ['/login'])
])


@router.before_request
def audit(ctx, request):
    logging.info(request.path)
    return request


def authenticated(fn):
    @wraps(fn)
    def wrap(ctx, request):
        token = request.headers.get('X-Authorization-Token')
        if token is None:
            raise HTTPUnauthorized()
Esempio n. 6
0
from m import Router
from m.security import Require
from m.utils import jsonify
from ..models import db, Comment, Post
from webob import exc
import datetime
import logging

router = Router('/api/comment')


@router.post('')
@Require()
def add_comment(ctx, request):
    try:
        payload = request.json()
        pid = payload['post']
        ref_id = payload.get('ref')
        content = payload['content']
    except Exception as e:
        raise exc.HTTPBadRequest(e)

    post = Post.query.filter(Post.id == pid).first_or_404(
        'post {} not found'.format(pid))
    ref = None
    if ref_id is not None:
        ref = Comment.query.filter(Comment.id == ref_id).first()
    comment = Comment(content=content,
                      user=request.principal.id,
                      ref=ref.id,
                      post=pid,
Esempio n. 7
0
from m import Router
from ..models import db, User, Catalog
from webob.exc import HTTPBadRequest, HTTPInternalServerError, HTTPUnauthorized
import bcrypt
from sqlalchemy import or_
from m.utils import jsonify
import logging
import jwt, bcrypt
import datetime


router = Router(prefix='/api')


@router.route(r'/register', methods=['POST'])
def register(ctx, request):
    try:
        payload = request.json()
        nickname = payload['nickname']
        mail = payload['mail']
        password = payload['password']
    except KeyError as e:
        raise HTTPBadRequest('{} is required'.format(e))
    except Exception as e:
        raise HTTPBadRequest(e)

    user = User.query.filter(or_(User.nickname == nickname, User.email == mail)).first()
    if user is not None:
        return jsonify(node=400, message='user exist')
    catalog = Catalog(name='default')
    user = User(nickname=nickname, catalogs=[catalog], email=mail, password=bcrypt.hashpw(password.encode(), bcrypt.gensalt()))
Esempio n. 8
0
from .models import db, User
from m import Router
from m.utils import jsonify

router = Router(prefix='')


@router.route('/', methods=['POST'])
def home(ctx, request):
    name = request.json().get('name')
    user = User(name=name)
    db.session.add(user)
    try:
        db.session.commit()
    except Exception as e:
        print(e)
        db.session.rollback()


@router.route('/{name}', methods=['GET'])
def get(ctx, request):
    name = request.args.get('name')
    user = User.query.filter(User.name == name).first_or_404(
        'user {} not exist'.format(name))
    return jsonify(code=200, user=user.dictify())
Esempio n. 9
0
import jwt
import json
import datetime
from m import Router, Application
from m.utils import jsonfy
from webob import Response
from functools import wraps
from webob.exc import HTTPUnauthorized

__KEY = 'dsjfhjkaSFHJKHSA'

router = Router()


def authenticated(fn):
    @wraps(fn)
    def wrap(ctx, request):
        token = request.headers.get('X-Authorization-Token')
        if token is None:
            raise HTTPUnauthorized()
        try:
            decoded = jwt.decode(token.encode(), __KEY, ['HS512'])
            user = decoded.get('user')
            if user is None:
                raise HTTPUnauthorized()
            request.user = user
            return fn(ctx, request)
        except Exception:
            raise HTTPUnauthorized()

    return wrap
Esempio n. 10
0
import jwt
import bcrypt
import logging
import datetime
from m import Router
from ..models import db, User, Catalog
from webob.exc import HTTPBadRequest, HTTPInternalServerError, HTTPUnauthorized
from sqlalchemy import or_
from m.utils import jsonify

router = Router(prefix='/api/user')


@router.post('/register')
def register(ctx, request):
    try:
        payload = request.json()
        nickname = payload['nickname']
        mail = payload['mail']
        password = payload['password']
    except KeyError as e:
        raise HTTPBadRequest('{} is required'.format(e))
    except Exception as e:
        raise HTTPBadRequest(e)
    user = User.query.filter(or_(User.nickname == nickname,
                                 User.mail == mail)).first()
    if user is not None:
        return jsonify(code=400, message='user exist')

    catalog = Catalog(name='notes')
    user = User(nickname=nickname,