def get_now_time2():
    return time.strftime("%Y-%m-%d %H-%M-%S",time.localtime(time.time())) def Info2RW(value):
    if (value=='write'):
        return '读写'
    elif(value=='readonly'):
        return '只读'
    elif(value=='none'):
        return '禁止'
    elif(value==''):
            return '禁止'    
    elif(value=='r'):
            return '只读'    
    elif(value=='rw'):
            return '读写'   
    elif(value=='禁止'):
            return ' '    
    elif(value=='只读'):
            return 'r'    
    elif(value=='读写'):
            return 'rw'     
    else:
        return "参数错误" def get_auths(type,reponame):
    auths=[]
    conn = engine.connect()
    if type=='user':
        if reponame=='irepresentalltherepos':
            sql = 'select reponame,authitem,username,authtype from auth_users cross join users,repos,auth_items where auth_users.user_id=users.id and auth_users.authitem_id = auth_items.id and auth_items.repo_id = repos.id order by reponame,authitem,username,authtype'
        else:
            sql = 'select reponame,authitem,username,authtype from auth_users cross join users,repos,auth_items where auth_users.user_id=users.id and auth_users.authitem_id = auth_items.id and auth_items.repo_id = repos.id and repos.reponame = \'' + reponame +'\' order by reponame,authitem,username,authtype'
        rs = conn.execute(sql)
        for r in rs:
            #print(r)
            auths.append({'reponame':r.reponame,'authitem':r.authitem,'username':r.username,'authtype':r.authtype}) 
    elif type=='group':
        if reponame=='irepresentalltherepos':
            sql = 'select reponame,authitem,groupname,authtype from auth_groups cross join groups,repos,auth_items where auth_groups.group_id=groups.id and auth_groups.authitem_id = auth_items.id and auth_items.repo_id = repos.id order by reponame,authitem,groupname,authtype'
        else:
            sql = 'select reponame,authitem,groupname,authtype from auth_groups cross join groups,repos,auth_items where auth_groups.group_id=groups.id and auth_groups.authitem_id = auth_items.id and auth_items.repo_id = repos.id and repos.reponame = \'' + reponame +'\' order by reponame,authitem,groupname,authtype'    
        rs = conn.execute(sql)
        for r in rs:
            #print(r)
            auths.append({'reponame':r.reponame,'authitem':r.authitem,'groupname':r.groupname,'authtype':r.authtype}) 
    return auths def get_user_groups(reponame):
    user_groups=[]
    conn = engine.connect()
    if reponame=='irepresentalltherepos':
        sql = 'select groupname,username from auth_groups cross join uig,groups,users,repos,auth_items where auth_groups.group_id=groups.id and auth_groups.authitem_id = auth_items.id and auth_items.repo_id = repos.id and uig.user_id = users.id and uig.group_id = groups.id order by reponame,username'
    else:
        sql = 'select groupname,username from auth_groups cross join uig,groups,users,repos,auth_items where auth_groups.group_id=groups.id and auth_groups.authitem_id = auth_items.id and auth_items.repo_id = repos.id and uig.user_id = users.id and uig.group_id = groups.id and repos.reponame = \'' + reponame +'\' order by reponame,username'
    rs = conn.execute(sql)
    groups = set([])
    for r in rs:
        groups.add(r.groupname)
    names = locals()
    for group in groups:
        names['%s' % group] = {'groupname':group,'users':''}
        names['users_%s' % group] = ''
        rs = conn.execute(sql)
        for r in rs:
            if r.groupname == group:
                names['users_%s' % group]=names['users_%s' % group]+','+r.username
        names['%s' % group]['users']=list(set((names['users_%s' % group].lstrip(',')).split(',')))
        names['%s' % group]['users'] = ','.join(names['%s' % group]['users'])
        user_groups.append(names['%s' % group])
    return user_groups def get_user_passwd(reponame):
    users=[]
    conn = engine.connect()
    if reponame=='irepresentalltherepos':
        sql = 'select username,password from users'
    else:
        sql = 'select username,password from users cross join auth_users,repos,auth_items where auth_users.user_id=users.id and auth_users.authitem_id = auth_items.id and auth_items.repo_id = repos.id and repos.reponame = \'' + reponame +'\' order by reponame,authitem,username,authtype'
    rs = conn.execute(sql)
    for r in rs:
        users.append({'username':r.username,'password':r.password})
    #print(users)
    return users def GetData(type,para):
    conn = engine.connect()
    #单项配置项数据
    if type == 'authitemid':
        authitem=[]
        sql = 'select auth_items.id as id,reponame,authitem FROM auth_items CROSS JOIN repos where auth_items.repo_id = repos.id \
        and repos.reponame = \'' + para[0] +'\' and auth_items.authitem = \'' + para[1] + '\' order by reponame,authitem'
        #print(sql)
        rs = conn.execute(sql)
        for r in rs:
            #print(r)
            authitem.append(r)
            return r[0]
    elif type == 'authiteminfo':
        authitem=[]
        sql = 'select reponame,authitem FROM auth_items CROSS JOIN repos where auth_items.repo_id = repos.id \
        and auth_items.id = \'' + para[0] + '\' order by reponame'
        #print(sql)
        rs = conn.execute(sql)
        for r in rs:
            #print(r)
            authitem.append(r)
            return authitem
    elif type == 'authitems':
        authitems=[]
        if para=='all':
            sql = 'select auth_items.id as id,reponame,authitem FROM auth_items CROSS JOIN repos where auth_items.repo_id = repos.id order by reponame,authitem'            
        else:
            sql = 'select auth_items.id as id,reponame,authitem FROM auth_items CROSS JOIN repos where auth_items.repo_id = repos.id and \
            repos.reponame like \'%' + para + '%\' order by reponame,authitem'
        #print(sql)
        rs = conn.execute(sql)
        for r in rs:
            #print(r)
            authitems.append(r)
        #print(authitems)
        return authitems
    elif type == 'users-json':
        users=[]
        if para=='all':
            sql = 'select id,fullname,username FROM users order by username'            
        else:
            pass
        #print(sql)
        rs = conn.execute(sql)
        for r in rs:
            #print(r)
            users.append({'id':r.id,'name':r.fullname + ' (' + r.username + ' )'})
        json_users = json.dumps(users)
        #print(users)
        #print(json_users)
        return json_users
    elif type == 'groups-json':
            groups=[]
            if para=='all':
                sql = 'select id,groupname FROM groups order by groupname'
            else:
                pass
            rs = conn.execute(sql)
            for r in rs:
                #print(r)
                groups.append({'id':r.id,'name':r.groupname})
            json_groups = json.dumps(groups)
            #print(groups)
            #print(json_groups)
            return json_groups 
    elif type == 'repos-json':
            repos=[]
            if para=='all':
                sql = 'select id,reponame FROM repos order by reponame'
            else:
                pass
            rs = conn.execute(sql)
            for r in rs:
                #print(r)
                repos.append({'id':r.id,'name':r.reponame})
            json_repos = json.dumps(repos)
            #print(repos)
            #print(json_repos)
            return json_repos   
    elif type == 'repos':
            repos=[]
            if para=='all':
                sql = 'select id,reponame FROM repos order by reponame'
            else:
                pass
            rs = conn.execute(sql)
            for r in rs:
                #print(r)
                repos.append(r.reponame)
            return repos  class HtpasswdUser(object):
    def __init__(self, userdb, mode='md5'):
        self.encryption_mode = mode
        self.userdb = userdb
        self.initial_users = OrderedDict()
        self.new_users = OrderedDict()

    def __enter__(self):
        with open(self.userdb, "r") as users:
            for i in users:
                user, password = i.split(":", 1)
                self.initial_users[user] = password
        self.new_users = self.initial_users.copy()
        return self

    def __exit__(self, type, value, traceback):
        if self.new_users == self.initial_users:
            return
        with open(self.userdb, "w") as userdb:
            for user in self.new_users:
                userdb.write("%s:%s" % (user, self.new_users[user]))

    def __contains__(self, user):
        return user in self.users

    @property
    def users(self):
        #返回用户的key
        return list(self.new_users.keys())

    def add(self, user, password):
        #添加用户
        if self.__contains__(user):
            self.change_password(user,password)
        self.new_users[user] = str(self._encrypt_password(password)) + "\n"

    def pop(self, user):
        #删除用户
        if not self.__contains__(user):
            pass
        self.new_users.pop(user)

    def change_password(self, user, password):
        #修改密码
        if not self.__contains__(user):
            self.add(user,password)
        self.new_users[user] = str(self._encrypt_password(password)) + "\n"

    def _encrypt_password(self, password):
        #
        if self.encryption_mode.lower() == 'crypt':
            return self._crypt_password(password)
        elif self.encryption_mode.lower() == 'md5':
            return self._md5_password(password)
        else:
            raise UnknownEncryptionMode(self.encryption_mode)

    def _crypt_password(self, password):
        """ Crypts password """

        def salt():
            """ Generates some salt """
            symbols = ascii_letters + digits
            return choice(symbols) + choice(symbols)

        #return crypt(password, salt())

    def _md5_password(self, password):
        """ Crypts password using openssl binary and MD5 encryption """
        return subprocess.check_output(['openssl', 'passwd', '-apr1', password]).decode('utf-8').strip() REPOS_DIRS='d:\SVNMaster\Repos\\' REPOS_BASE_URL='http://127.0.0.1/svn/' SVN_HTTPD_AUTHZ = 'd:\SVNMaster\Repos\\authz' SVN_HTTPD_USERS = 'd:\SVNMaster\Repos\\htpasswd' SVN_AUTH_MODE = 'httpd'
import os,os.path,time, platform,re,configparser,codecs,shutil,subprocess
from mos.utils.functions import get_now_time2,Info2RW
from mos.utils.database import get_auths,get_user_groups,get_user_passwd,GetData
from mos.utils.htpasswd import HtpasswdUser
from config import REPOS_DIRS,REPOS_BASE_URL,SVN_HTTPD_AUTHZ,SVN_HTTPD_USERS,SVN_AUTH_MODE
#!/usr/bin/env python
# -*- coding: utf-8 -*- 
__author__="EIXXIE"


#创建UTF-8编码的文件，因为authz文件中可能包含中文
def create_new_file(path,code):
    f = codecs.open(path,'a',code)
    #f.write(u'中文')
    f.close()

#检查文件是否存在
def check_file_exists(filepath):
    #如果文件已经存在，则重命名之
    if os.path.isfile(filepath):
        os.rename(filepath,filepath + '.' + get_now_time2())
    create_new_file(filepath, 'utf-8')

#httpd方式下，新增用户
def add_httpd_user(username,password):
    if os.path.isfile(SVN_HTTPD_USERS):

        shutil.copyfile(SVN_HTTPD_USERS,SVN_HTTPD_USERS + '.' + get_now_time2())