Repository navigation
Expand file tree
/
Copy pathinit_databases.py
More file actions
executable file
·197 lines (155 loc) · 6.27 KB
/
Copy pathinit_databases.py
File metadata and controls
executable file
·197 lines (155 loc) · 6.27 KB
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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# init_databases.py - Create and update Mycodo SQLite databases
#
# Copyright (C) 2015 Kyle T. Gabriel
#
# This file is part of Mycodo
#
# Mycodo is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mycodo is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mycodo. If not, see <http://www.gnu.org/licenses/>.
#
# Contact at kylegabriel.com
import argparse
import getpass
import os
import sys
import sqlalchemy
from mycodo.config import SQL_DATABASE_USER, SQL_DATABASE_NOTE, SQL_DATABASE_MYCODO
from mycodo.databases.users_db.models import Users
from mycodo.databases.utils import session_scope
from mycodo.scripts.utils import test_username, test_password, is_email, query_yes_no
if sys.version[0] == "3":
raw_input = input # Make sure this works in PY3
USER_DB_PATH = 'sqlite:///' + SQL_DATABASE_USER
MYCODO_DB_PATH = 'sqlite:///' + SQL_DATABASE_MYCODO
NOTES_DB_PATH = 'sqlite:///' + SQL_DATABASE_NOTE
def add_user(admin=False):
new_user = Users()
print('\nAdd user to database')
while True:
user_name = raw_input('User (a-z, A-Z, 2-64 chars): ')
if test_username(user_name):
new_user.user_name = user_name
break
while True:
user_password = getpass.getpass('Password: ')
user_password_again = getpass.getpass('Password (again): ')
if user_password != user_password_again:
print("Passwords don't match")
else:
if test_password(user_password):
new_user.set_password(user_password)
break
while True:
user_email = raw_input('Email: ')
if is_email(user_email):
new_user.user_email = user_email
break
if admin:
new_user.user_restriction = 'admin'
else:
new_user.user_restriction = 'guest'
new_user.user_theme = 'dark'
try:
with session_scope(USER_DB_PATH) as db_session:
db_session.add(new_user)
sys.exit(0)
except sqlalchemy.exc.OperationalError:
print("Failed to create user. You most likely need to "
"create the DB before trying to create users.")
sys.exit(1)
except sqlalchemy.exc.IntegrityError:
print("Username already exists.")
sys.exit(1)
def delete_user(username):
if query_yes_no("Confirm delete user '{}' from user database.".format(username)):
try:
with session_scope(USER_DB_PATH) as db_session:
user = db_session.query(Users).filter(Users.user_name == username).one()
db_session.delete(user)
print("User deleted.")
sys.exit(0)
except sqlalchemy.orm.exc.NoResultFound:
print("No user found with this name.")
sys.exit(1)
def change_password(username):
print('Changing password for {}'.format(username))
with session_scope(USER_DB_PATH) as db_session:
user = db_session.query(Users).filter(Users.user_name == username).one()
while True:
user_password = getpass.getpass('Password: ')
user_password_again = getpass.getpass('Password (again): ')
if user_password != user_password_again:
print("Passwords don't match")
else:
try:
if test_password(user_password):
user.set_password(user_password)
sys.exit(0)
except sqlalchemy.orm.exc.NoResultFound:
print("No user found with this name.")
sys.exit(1)
def create_dbs(db_name, create_all=False):
if not os.path.exists(os.path.dirname(SQL_DATABASE_USER)):
try:
os.makedirs(os.path.dirname(SQL_DATABASE_USER))
except OSError as exc: # Guard against race condition
if exc.errno != errno.EEXIST:
raise
if db_name == 'mycodo' or create_all:
print("Creating/verifying {} at {} ...".format(db_name, MYCODO_DB_PATH))
from mycodo.databases.mycodo_db import init_db
from mycodo.databases.mycodo_db import populate_db
init_db(MYCODO_DB_PATH)
populate_db(MYCODO_DB_PATH)
if db_name == 'notes' or create_all:
print("Creating/verifying {} at {} ...".format(db_name, NOTES_DB_PATH))
from mycodo.databases.notes_db import init_db
init_db(NOTES_DB_PATH)
if db_name == 'users' or create_all:
print("Creating/verifying {} at {} ...".format(db_name, USER_DB_PATH))
from mycodo.databases.users_db import init_db
init_db(USER_DB_PATH)
sys.exit(0)
def menu():
parser = argparse.ArgumentParser(description="Initialize Mycodo Database "
"structure and manage users")
parser.add_argument('-i', '--install_db', type=str,
choices=['users', 'mycodo', 'notes', 'all'],
help="Create new users.db, mycodo.db and/or note.db")
parser.add_argument('-A', '--addadmin', action='store_true',
help="Add admin user to users database")
parser.add_argument('-a', '--adduser', action='store_true',
help="Add user to users database")
parser.add_argument('-d', '--deleteuser',
help="Remove user from users database")
parser.add_argument('-p', '--pwchange',
help="Create a new password for user")
args = parser.parse_args()
if args.adduser:
add_user()
if args.addadmin:
add_user(admin=True)
if args.install_db:
if args.install_db == 'all':
create_dbs('', create_all=True)
else:
create_dbs(args.install_db)
if args.deleteuser:
delete_user(args.deleteuser)
if args.pwchange:
change_password(args.pwchange)
if __name__ == "__main__":
menu()