From 5459916e15a3cd288bd2df8058bb39334f74fab9 Mon Sep 17 00:00:00 2001 From: Denis Zheleztsov Date: Sat, 9 Sep 2017 15:08:45 +0300 Subject: [PATCH] Users add/del script --- users.py | 68 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 users.py diff --git a/users.py b/users.py new file mode 100644 index 0000000..c1bc15a --- /dev/null +++ b/users.py @@ -0,0 +1,68 @@ +#!/usr/bin/env python + +import argparse +import bcrypt +import sqlite3 + + +def parse_command_line(): + parser = argparse.ArgumentParser() + parser.add_argument("-u", "--user", + help="User name") + parser.add_argument("-p", "--password", + help="User password. If it none password will be generated") + parser.add_argument("-b", "--database", default="./auth.db", help="Path to users database") + parser.add_argument("--delete", action='store_true', help="Delete user") + return parser.parse_args() + + +class User: + + def __init__(self, args): + self.args = args + self.user = args.user + self.password = args.password + self.connection = self._init_connection() + + def _init_connection(self): + con = sqlite3.connect(self.args.database) + cur = con.cursor() + return {"cursor": cur, "connect": con} + + def _close_connection(self): + self.connection["cursor"].close() + self.connection["connect"].close() + + def _commit(self): + self.connection["connect"].commit() + + def add(self): + if self.password is None: + self.password = self._passgen() + hashed_password = bcrypt.hashpw(self.password.encode('utf-8'), bcrypt.gensalt()) + self.connection["cursor"].execute( + "INSERT INTO users (name, password) VALUES (?, ?)", + (self.user, hashed_password) + ) + self._commit() + self._close_connection() + + def delete(self): + self.connection["cursor"].execute( + "DELETE FROM users WHERE name=?", + (self.user,) + ) + self._commit() + self._close_connection() + + def _passgen(self): + pass + + +if __name__ == "__main__": + args = parse_command_line() + user = User(args) + if not args.delete: + user.add() + else: + user.delete()