LSF/session.go

76 lines
2.1 KiB
Go
Raw Normal View History

2019-10-05 20:32:39 +02:00
package lsf
import (
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
"github.com/pkg/errors"
)
type Session struct {
SID string
}
func (s *Session) Valid() (bool, error) {
client := &http.Client{}
req, err := http.NewRequest("GET", "https://lsf.hs-worms.de/qisserver/rds?state=user&type=8&topitem=functions&breadCrumbSource=portal", nil)
if err != nil {
return false, errors.Wrap(err, "could not prepare the request")
}
req.Header.Add("Cookie", fmt.Sprintf("JSESSIONID=%s", s.SID))
resp, err := client.Do(req)
if err != nil {
return false, errors.Wrap(err, "could not do the request")
}
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return false, errors.Wrap(err, "could not read the response body")
}
if strings.Contains(string(b), "<u>L</u>ogout") {
return true, nil
}
if strings.Contains(string(b), "<u>L</u>ogin") {
return false, nil
}
return false, errors.New("unexpected response body")
}
func Login(username, password string) (*Session, error) {
client := &http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error { // don't follow redirects
return http.ErrUseLastResponse
},
}
form := url.Values{}
form.Add("asdf", username) // who wrote this backend? lol
form.Add("fdsa", password)
form.Add("submit", "Login")
req, err := http.NewRequest("POST", "https://lsf.hs-worms.de/qisserver/rds?state=user&type=1&category=auth.login&startpage=portal.vm&breadCrumbSource=portal", strings.NewReader(form.Encode()))
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
if err != nil {
return nil, errors.Wrap(err, "could not prepare the login request")
}
resp, err := client.Do(req)
if err != nil {
return nil, errors.Wrap(err, "could not do the login request")
}
if resp.StatusCode == 302 {
for _, c := range resp.Cookies() {
if c.Name == "JSESSIONID" {
return &Session{
SID: c.Value,
}, nil
}
}
return nil, errors.New("no session cookie found")
}
if resp.StatusCode == 200 {
return nil, errors.New("wrong credentials") // TODO or other errors
}
return nil, errors.New("unexpected response status code")
}