Skip to content

Commit

Permalink
适应性视频-提供SSO登录方式
Browse files Browse the repository at this point in the history
  • Loading branch information
chenli committed Sep 7, 2021
1 parent cfafedf commit 68d94fd
Show file tree
Hide file tree
Showing 4 changed files with 170 additions and 4 deletions.
12 changes: 9 additions & 3 deletions greener_classes/classes/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@
- JSESSIONID
- stu_token

## 1.获取所需参数:
## 方一(旧版):

### 1.获取所需参数:

> 选择下列一种即可,推荐第一种
Expand All @@ -19,8 +21,12 @@

![](https://i.loli.net/2021/08/23/LiudKFgpBrNkqn3.png)

## 2.执行程序
### 2.执行程序

在脚本所在目录打开命令行,输入:` python zju_guide_class.py -s 获取的JSESSIONID -t 获取的STU_TOKEN`

![](https://i.loli.net/2021/08/23/VtS7DH2PyGM8hsc.png)
![](https://i.loli.net/2021/08/23/VtS7DH2PyGM8hsc.png)

## 方二(2021年9月7日更新):

运行通过统一认证平台登录获得信息从而运行的程序: `python guide_class_login.py`
50 changes: 50 additions & 0 deletions greener_classes/classes/guide_class_login.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/9/7 13:32
# @Author : Mrli
# @File : guide_class_login.py
import time
from loginUtils import SSOLogin


class GuideClass(SSOLogin):
def getAllCourses(self):
params = (
('t', str(int(round(time.time() * 1000)))),
('title', ''),
('isRequired', ''),
)
response = self.sess.get('http://regi.zju.edu.cn/grs-pro/config/vclassesdetail/queryList',
params=params, verify=False)
return response.json().get("list")

def passClass(self, class_id: str) -> None:
self.sess.headers["Referer"] = 'http://regi.zju.edu.cn/classDetail?id={}'.format(class_id)
params = (
('t', str(int(round(time.time() * 1000)))),
('studyTime', str(1000)),
('classId', class_id),
)
response = self.sess.post('http://regi.zju.edu.cn/grs-pro/stu/classinfo/addStudyLog',
params=params, verify=False)
print(response.text)

def run(self):
self.sso_login()
all_courses = self.getAllCourses()
for c in all_courses:
self.passClass(c.get("id"))


if __name__ == '__main__':
# if len(sys.argv) < 2:
# print("请输入学号、密码")
# username, password = sys.argv[1], sys.argv[2]
in_str = input("请输入学号、密码(空格分割):").split()
if len(in_str) == 2:
username, password = in_str
else:
raise Exception("请分别输入学号与密码(空格分割)")

gc = GuideClass(username, password)
gc.run()
111 changes: 111 additions & 0 deletions greener_classes/classes/loginUtils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
import requests
import re
import time
import urllib.parse as urlparse


# Exceptions
class LoginError(Exception):
"""Login Exception"""
pass


class ZJULogin(object):
"""
统一认证平台的登录使用的ZJU-nCov-Hitcarder的开源代码,感谢这位同学开源对RSA加密的贡献
Attributes:
username: (str) 浙大统一认证平台用户名(一般为学号)
password: (str) 浙大统一认证平台密码
login_url: (str) 登录url
sess: (requests.Session) 统一的session管理
"""

def __init__(self, username, password):
self.username = username
self.password = password
self.login_url = "https://zjuam.zju.edu.cn/cas/login?service=http%3A%2F%2Fservice.zju.edu.cn%2F"
self.sess = requests.Session()

def login(self):
"""Login to ZJU platform"""
res = self.sess.get(self.login_url)
execution = re.search(
'name="execution" value="(.*?)"', res.text).group(1)
res = self.sess.get(
url='https://zjuam.zju.edu.cn/cas/v2/getPubKey').json()
n, e = res['modulus'], res['exponent']
encrypt_password = self._rsa_encrypt(self.password, e, n)

data = {
'username': self.username,
'password': encrypt_password,
'execution': execution,
'_eventId': 'submit',
"authcode": ""
}
res = self.sess.post(url=self.login_url, data=data)
# check if login successfully
if '统一身份认证' in res.content.decode():
raise LoginError('登录失败,请核实账号密码重新登录')
print("统一认证平台登录成功")
return self.sess

def _rsa_encrypt(self, password_str, e_str, M_str):
password_bytes = bytes(password_str, 'ascii')
password_int = int.from_bytes(password_bytes, 'big')
e_int = int(e_str, 16)
M_int = int(M_str, 16)
result_int = pow(password_int, e_int, M_int)
return hex(result_int)[2:].rjust(128, '0')


class SSOLogin(ZJULogin):
"""
完成测试需要获得token
"""
def sso_login(self):
"""
获得token,并在请求头上加上token
Returns: token
"""

def substract_query_params(url):
parsed = urlparse.urlparse(url)
querys = urlparse.parse_qs(parsed.query)
return {k: v[0] for k, v in querys.items()}

def get_code():
params = (
('response_type', 'code'),
('client_id', 'kU3pGMMUuXK3zFmnMY'),
('redirect_uri', 'http://regi.zju.edu.cn/ssologin'),
)

response = self.sess.get('https://zjuam.zju.edu.cn/cas/oauth2.0/authorize', params=params)
location = ""
for r in response.history:
if "location" in r.headers:
location = r.headers.get("location")
return substract_query_params(location).get("code")

# 获得cookies
self.login()
# 获得sso_login所需的code
code = get_code()
params = (
('t', int(round(time.time() * 1000))),
('code', code),
('role', 'student'),
)
response = self.sess.get('http://regi.zju.edu.cn/grs-pro/zs/auth/ssoLogin', params=params, verify=False)
token = response.json().get("token")
self.sess.headers["token"] = token
return token


if __name__ == "__main__":
login = ZJULogin(username="*", password="*")
print("登录到浙大统一身份认证平台...")
res = login.login()
print(res.headers)
print(res.cookies)
1 change: 0 additions & 1 deletion greener_classes/questions/main_script.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import json
import time
import sys
from loginUtils import SSOLogin


Expand Down

0 comments on commit 68d94fd

Please sign in to comment.