python登录认证后端接口开发

实现基于ldap认证登录认证以及token认证:

主要库:flask ,mongo,redis,ldap

1.代码

1.1目录结构
auth-manage
├── bin
│   ├── start.sh
│   └── stop.sh
├── conf
│   └── conf.ini
├── data
├── logs
│   └── auth-manage.log
└── project
    ├── auth_api.py
    └── auth_manage.py
1.2启停脚本

1.2.1 启动脚本start.sh

#!/bin/sh
basepath=$(cd `dirname $0`; pwd)
echo $basepath
nohup python3 $basepath/../project/auth_api.py 2>&1 /dev/null &

1.2.2停止脚本stop.sh

#!/bin/bash
name='auth_api.py'
pid=$(ps -ef|grep "../project/$name"|grep -v grep|awk '{print $2}')
if [ -z "$pid" ];then
    echo 'process is not alived'
else
    echo 'kill process'
    kill -9 $pid
    pid=$(ps -ef|grep "../project/$name"|grep -v grep|awk '{print $2}')
    if [ -z "$pid" ];then
        echo 'kill process success'
    else
        echo 'kill process error'
    fi
fi

1.3配置文件conf.ini
[log]
loglevel = debug
logname = auth-manage.log
interval = 1
backupCount = 7
when = MIDNIGHT
encoding = utf-8

[mongodb]
host = xxxxx
dbname = devops
user = xxxxx
password = xxxx

[ldap]
host = xxxx.com
port = 389
base_dn = ou=xxx,dc=xxxx,dc=com
user_dn = cn=xxx,ou=Public,dc=xxxx,dc=com
password = xxxxx

[redis]
host = xxxxxx
port = 6379
db = 0
redis_expire = 3600
password = xxxxxx

1.4工程代码auth_manage.py
# -*- coding: UTF-8 -*-

import os
import sys
import time
import logging
import configparser
import re
from logging.handlers import TimedRotatingFileHandler
import json
import requests
from multiprocessing import Process,Lock
import threading
import hashlib
import datetime
import pymongo
from pymongo import MongoClient, DESCENDING
from bs4 import BeautifulSoup
from ldap3 import (
    Server,
    Connection,
    SUBTREE,
    LEVEL,
    ALL_ATTRIBUTES,
    RESTARTABLE,
    SAFE_RESTARTABLE,
    MODIFY_REPLACE,
    MODIFY_DELETE,
)
from ldap3.protocol.microsoft import show_deleted_control
from ldap3.utils.dn import safe_rdn
from ldap3.core.exceptions import LDAPException, LDAPInvalidCredentialsResult
import redis
import base64






BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
CONF_PATH = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),'conf','conf.ini')


def getNowTime():
    return time.strftime(r'%Y%m%d%H%M%S',time.localtime(time.time()))


class param():
    def __init__(self,confPath):
#        self.conf = configparser.ConfigParser()
        self.conf = configparser.RawConfigParser()
        self.conf.read(confPath)
        self.log_init()
        self.mongodb_init()
        self.ldap_init()
        self.redis_init()

    def log_init(self):
        self.log = {}
        self.log['loglevel'] = self.conf.get('log','loglevel')
        self.log['logname'] = self.conf.get('log','logname')
        self.log['interval'] = self.conf.getint('log','interval')
        self.log['backupCount'] = self.conf.getint('log','backupCount')
        self.log['when'] = self.conf.get('log','when')
        self.log['encoding'] = self.conf.get('log','encoding')

    def mongodb_init(self):
        self.mongodb = {}
        self.mongodb['host'] = self.conf.get('mongodb','host').split(',')
        self.mongodb['dbname'] = self.conf.get('mongodb','dbname')
        self.mongodb['user'] = self.conf.get('mongodb','user')
        self.mongodb['password'] = self.conf.get('mongodb','password')

    def ldap_init(self):
        self.ldap = {}
        self.ldap['host'] = self.conf.get('ldap','host')
        self.ldap['port'] = int(self.conf.get('ldap','port'))
        self.ldap['base_dn'] = self.conf.get('ldap','base_dn')
        self.ldap['user_dn'] = self.conf.get('ldap','user_dn')
        self.ldap['password'] = self.conf.get('ldap','password')

    def redis_init(self):
        self.redis = {}
        self.redis['host'] = self.conf.get('redis','host')
        self.redis['port'] = self.conf.get('redis','port')
        self.redis['db'] = self.conf.get('redis','db')
        self.redis['password'] = self.conf.get('redis','password')
        self.redis['redis_expire'] = self.conf.get('redis','redis_expire')


class Auth():
    def __init__(self,conf_path):
        self.param = param(conf_path)
        # log
        self.param.log['logname'] = os.path.join(BASE_DIR,'logs',self.param.log['logname'])
        self.logger_init(**self.param.log)
        self.mongodb_init(**self.param.mongodb)
        self.ldap_init(**self.param.ldap)
        self.redis_init(**self.param.redis)

    # 初始化部分-------
    def logger_init(self,loglevel,logname,interval,backupCount,when,encoding):
        logger = logging.getLogger('log')
        logger.setLevel(logging.DEBUG)

        # 移除掉所有的handler
        while logger.hasHandlers():
            for i in logger.handlers:
                logger.removeHandler(i)

        # file log
        formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
        fh = TimedRotatingFileHandler(logname, when=when, interval=interval, backupCount=backupCount,encoding=encoding)
        fh.setLevel(logging.DEBUG)
        fh.setFormatter(formatter)
        logger.addHandler(fh)

        # console log
        self.logger = logger

    def redis_init(self,host,port,db,password,redis_expire):
        self.logger.debug("begin init redis connection")
        try:
            self.redis_expire = int(redis_expire)
            self.redis_cli = redis.Redis(host=host, port=port, db=db,password=password,decode_responses=True)
#            self.redis_cli = redis.Redis(host=host, port=port, db=db,password=password)
        except Exception as e:
            self.logger.error("Failed to connect to redis!")
            self.logger.error(str(e))
            raise e
        self.logger.debug("connect to redis success!")

    def ldap_init(self,host, port, user_dn, password, base_dn):
        self.logger.debug("begin init ldap connection")
        try:
#            self.server = Server(host=host, port=port, use_ssl=True)
            self.server = Server(host=host, port=port)
            self.base_dn = base_dn
            self.conn = Connection(
                self.server,
                user_dn,
                password,
                check_names=True,
                auto_bind=False,
                raise_exceptions=True,
            )
        except Exception as e:
            self.logger.error("Failed to connect to ldap!")
            self.logger.error(str(e))
            raise e
        self.logger.debug("connect to ldap success!")


    def mongodb_init(self,host,dbname,user,password):
        self.logger.debug("begin init mongodb connection")
        try:
            self.client = pymongo.MongoClient(host)
            self.db = self.client[dbname]
            self.db.authenticate(user,password)
        except Exception as e:
            self.logger.error("Failed to connect to MongoDB!")
            self.logger.error(str(e))
            raise e
        self.logger.debug("connect to MongoDB success!")


    def auth_by_ldap(self, name, password):
        allowed_page = []
        try:
            self.conn.rebind()
            search_res = self.conn.search(
                                     search_base=self.base_dn,
                                     search_filter="(&(objectClass=person)(sAMAccountName={}))".format(name),
                                     search_scope=SUBTREE,
                                     attributes=["objectGUID", "sAMAccountName"],
                                     )
            if search_res:
                entry = self.conn.response[0]
            else:
                entry = ""

            self.conn.unbind()

        except Exception as e:
            self.logger.error(f"search res error as:  {e}")
            search_res = ""
            entry = ""
        if search_res:
            user_dn = entry["dn"]

            try:
                # 这个connect是通过你的用户名和密码还有上面搜到的入口搜索来查询的

                user_conn = Connection(
                                          self.server,
                                          user=user_dn,
                                          password=password,
                                          check_names=True,
                                          auto_bind=False,
                                          raise_exceptions=True,
                                          )
                self.logger.debug(str(user_conn))
                user_conn.rebind()
                user_conn.unbind()

            except LDAPInvalidCredentialsResult as e:
                self.logger.error(str(e))
                error_txt = ""
                if "52e" in e.message:
                    error_txt = "密码不正确!"
                elif "775" in e.message:
                    error_txt = "账号已锁定, 请联系管理员或等待自动解锁!"
                elif "533" in e.message:
                    error_txt = "账号已禁用!"
                elif "773" in e.message:
                    error_txt = "用户登陆前必须修改密码!"
                else:
                    error_txt = "认证失败, 请联系管理员检查该账号!"
                self.logger.error(error_txt)
                return(error_txt,allowed_page)



                # 正确-success 不正确-invalidCredentials
            if user_conn.result["description"] == "success":
                if "attributes" in entry:
                    rs = self.db.devopsuser.find_one({'username':name})
                    if rs:
                        result = self.db.devopsrole.find_one({'role':rs['role']})
                        normalpages = result['normalpage']
                        for np in normalpages:
                            if np:
                                if np["permission"] != "":
                                    allowed_page.append(np['nid'])
                        return('CORRECT',allowed_page)
                    else:
                        self.db.devopsuser.insert_one({'username':name,'role':'guest'})
                        result = self.db.devopsrole.find_one({'role':'guest'})
                        normalpages = result['normalpage']
                        for np in normalpages:
                            if np:
                                if np["permission"] != "":
                                    allowed_page.append(np['nid'])
                        return('CORRECT',allowed_page)

            else:
                self.logger.error('user_conn result data abnormal')
                return('user_conn result data abnormal',allowed_page)
        else:
            self.logger.error('search res faild')
            return('search res faild',allowed_page)


    def login(self,user_id):
        self.user_id = user_id
        result = generate_token()
        token = result[0]
        create_time = result[1]
        expire_time = result[2]

        if self.user_id == 'guest':
            self.redis_cli.set(self.user_id, token)
        else:
            self.redis_cli.set(self.user_id, token, ex=self.redis_expire)
        return token,create_time,expire_time

    def check(self, user_id,token):
        self.user_id = user_id
        if self.redis_cli.exists(self.user_id):
            timetoken = self.redis_cli.get(self.user_id)
            if timetoken == token:
                status = checkout_token(timetoken)
                if status == 1:
                    new_result = generate_token()
                    new_token = new_result[0]
                    create_time = new_result[1]
                    expire_time = new_result[2]
                    self.redis_cli.set(self.user_id, new_token,ex=self.redis_expire)
                    return("SUCCESS",new_token,create_time,expire_time)
                else:
                    return ("SESSION-EXPIRED","0","0","0")
            else:
                return ("INVALID-TOKEN","0","0","0")
        else:
            return ("FAILURE","0","0","0")


def md5(arg):
    md5_pwd = hashlib.md5(bytes('demaxiya', encoding='utf-8'))
    md5_pwd.update(bytes(arg, encoding='utf-8'))
    return md5_pwd.hexdigest()

def generate_token(aging=3600):
    sha1_token = hashlib.sha1(os.urandom(24)).hexdigest()
    create_time = int(time.time())
    time_group = str(create_time)+":"+str(aging)
    time_token = base64.urlsafe_b64encode(time_group.encode("utf-8")).decode("utf-8").strip().lstrip().rstrip('=')
    token = sha1_token+time_token
    expire_time = create_time + 3600
    return token,create_time,expire_time

def checkout_token(token):
    result = {}
    decode_time = safe_b64decode(token[40:]).decode('utf-8')
    decode_split_time = decode_time.split(':')
    decode_create_time = decode_split_time[0]
    decode_aging_time = decode_split_time[1]
    now_time = int(time.time())
    difference_time = now_time-int(decode_create_time)
    if difference_time > int(decode_aging_time):
        result = 0
    else:
        result = 1
    return result

def safe_b64decode(s):
    length = len(s) % 4
    for i in range(length):
        s = s+'='
    return base64.b64decode(s)

1.5 flask代码auth_api.py
# -*- coding: UTF-8 -*-

from flask import Flask, abort, request, make_response, jsonify, Response, render_template
from flask_cors import CORS
import json
import auth_manage
import os
import re


app = Flask(__name__)
UM = auth_manage.Auth(auth_manage.CONF_PATH)


@app.errorhandler(404)
def not_found(error):
    return make_response(jsonify({'error': 'Not found'}), 404)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/api/auth/login', methods=['GET', 'POST'])
def user_login():
    info = {}
    r_dict = {}
    token = "0"
    token_expire_time = "0"
    if request.method == 'POST':
        if request.json:
            userid = request.json['userid']
            passwd = request.json['passwd']
        else:
            userid = request.form['userid']
            passwd = request.form['passwd']
        result = UM.auth_by_ldap(userid, passwd)

        if result[0] == "CORRECT":
            result_token = UM.login(userid)
            token = result_token[0]
            token_expire_time = result_token[2]
#            r_dict['result'] = result[0]
            r_dict['token'] = token
            r_dict['page'] = result[1]
            r_dict['token_expire_time'] = str(token_expire_time)
            r_dict['userid'] = userid

            info['status'] = 200
            info['result'] = ""
            info['data'] = r_dict
            return json.dumps(info)
        else:
            info['status'] = 500
            info['result'] = result[0]
            info['data'] = ""
            return json.dumps(info)

    else:
        info['status'] = 500
        info['result'] = "please use POST request"
        info['data'] = ""
        return json.dumps(info)


@app.route('/api/auth/tokenauth', methods=['GET', 'POST'])
def token_check():
    info = {}
    r_dict = {}

    if request.method == 'POST':
        if request.json:
            userid = request.json['userid']
            token = request.json['token']
        else:
            userid = request.form['userid']
            token = request.form['token']

        result = UM.check(userid,token)
        if result[0] == "SUCCESS":
            r_dict['token'] = result[1]
            r_dict['token_expire_time'] = str(result[3])
            r_dict['userid'] = userid
            info['status'] = 200
            info['result'] = ""
            info['data'] = r_dict
            return json.dumps(info)
        else:
            info['status'] = 500
            info['result'] = result[0]
            info['data'] = ""
            return json.dumps(info)
    else:
        info['status'] = 500
        info['result'] = "please use POST request"
        info['data'] = ""
        return json.dumps(info)


if __name__ == '__main__':
    CORS(app, supports_credentials=True)
    app.run(host='0.0.0.0', port="10086",debug=True)




2.数据库表结构

2.1 表devopsuser 一条数据
{
    "_id" : ObjectId("62bd3f8bacf7357197acf178"),
    "role" : "admin",
    "username" : "zhangsan"
}
2.2 表devopsrole一条数据
{
    "_id" : ObjectId("62bc14c7029deb74beb1b7ba"),
    "role" : "admin",
    "normalpage" : [
        {
            "name" : "xxx",
            "nid" : "yyy",
            "permission" : "W"
        },
        {

        }
    ]
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,816评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,729评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 158,300评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,780评论 1 285
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,890评论 6 385
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,084评论 1 291
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,151评论 3 410
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,912评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,355评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,666评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,809评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,504评论 4 334
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,150评论 3 317
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,882评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,121评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,628评论 2 362
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,724评论 2 351