summaryrefslogtreecommitdiffstats
path: root/app.py
blob: decd9dfcc239f4671fe0c8ab6777b831de80b554 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
import shutil
from pathlib import Path

import flask
import markdown
from flask_caching import Cache
from flask_htpasswd import HtPasswdAuth
from flask_restful import reqparse, Api, Resource

from config import Config

app = flask.Flask(__name__)
api = Api(app)

# app config
if app.config["ENV"] == "development":
    app.config.from_object("config.DevelopConfig")
else:
    app.config.from_object(Config)

cache = Cache(app)
htpasswd = HtPasswdAuth(app)
htpasswd.users.autosave = True
parser = reqparse.RequestParser()

messages = {
    'OK': {
        'status': 200,
        'message': 'OK'
    },
    'Created': {
        'status': 201,
        'message': "User creation succeeded"
    },
    'Unauthorized Request': {
        'status': 401,
        'message': 'Unauthorized Request',
    },
    'Unprocessable Entity':{
        'status': 422,
        'message': 'Missing parameter'
    },
    'Conflict': {
        'status': 409,
        'message': 'Username conflict'
    },
    'InternalServerError': {
        'status': 500,
        'message': 'Something went wrong, please contact the administrator.'
    }
}


@app.route('/joplin/')
@cache.cached(timeout=21600)
def index():
    # codehilite css
    with open(Path(app.root_path).joinpath('./static/hilite.css'), 'r') as hilite_file:
        css = '<style>{css}</style>'.format(css=hilite_file.read())

    # Open the README file
    with open(Path(app.root_path).joinpath('./static/Readme.md'), 'r') as markdown_file:

        # Read the content of the file
        content = markdown_file.read()

    html = ''.join([css, content])

    # render finished HTML
    return flask.Response(markdown.markdown(html, extensions=["fenced_code", "codehilite"]), status=200)


@app.route('/joplin/auth-test')
@htpasswd.required
def auth_test(user):
    return 'Hello {user}'.format(user=user)


class NewUser(Resource):
    """
    class to create new htpasswd user entry
    """
    def post(self, username):
        parser.add_argument('password')
        parser.add_argument('invite')

        args = parser.parse_args()
        password = args['password']
        invitecode = args['invite']
        path = app.config['JOPLIN_DIR']

        # break early
        if invitecode != app.config['INVITE_CODE']:
            return flask.jsonify(messages['Unauthorized Request'])

        if None in [password, invitecode]:
            return flask.jsonify(messages['Unprocessable Entity'])
        
        if username not in htpasswd.users.users():
            # firstly try to create the folder to break if permissions aren't correct
            try:
                Path.mkdir(Path(path).joinpath('./%s' % username), mode=0o750, exist_ok=True)

            except OSError:
                return flask.jsonify(messages['InternalServerError'])
            # create user entry
            htpasswd.users.set_password(username, password)

            return flask.jsonify(messages['Created'])
        else:
            return flask.jsonify(messages['Conflict'])


class ChangePW(Resource):
    """
    class to update a users password
    """
    def post(self, username):
        parser.add_argument('password')
        parser.add_argument('new_password')

        args = parser.parse_args()
        password = args['password']
        new_password = args['new_password']

        if None in [password, new_password]:
            return flask.jsonify(messages['Unprocessable Entity'])

        # check_password return False if password mismatch and None if no user is found
        if htpasswd.users.check_password(username, password):
            htpasswd.users.update(username, new_password)

            return flask.jsonify(messages['OK'])
        else:
            return flask.jsonify(messages['Unauthorized Request'])


class DelUser(Resource):
    """
    class to delete a user
    """
    def delete(self, username):
        parser.add_argument('password')

        args = parser.parse_args()
        password = args['password']

        if password is None:
            return flask.jsonify(messages['Unprocessable Entity'])

        # check_password return False if password mismatch and None if no user is found
        if htpasswd.users.check_password(username, password):
            htpasswd.users.delete(username)

            try:
                # remove users files recursively
                shutil.rmtree(Path(app.config['JOPLIN_DIR']).joinpath('./%s' % username))
            except FileNotFoundError:
                pass

            return flask.Response(flask.jsonify([]), status=204)
        else:
            return flask.jsonify(messages['Unauthorized Request'])


api.add_resource(NewUser, '/joplin/<string:username>/create')
api.add_resource(ChangePW, '/joplin/<string:username>/changepw')
api.add_resource(DelUser, '/joplin/<string:username>')


if __name__ == '__main__':
    app.run()