Ejemplo n.º 1
0
// AuthenticateRequest authenticates the request using the "Authorization: Basic" header in the request
func (a *Authenticator) AuthenticateRequest(req *http.Request) (user.Info, bool, error) {
	username, password, found := req.BasicAuth()
	if !found {
		return nil, false, nil
	}
	return a.auth.AuthenticatePassword(username, password)
}
Ejemplo n.º 2
0
func (op *obtainTokenOp) parse(jp jsonParser, r *http.Request) error {
	v := mux.Vars(r)
	op.serverLocation = strings.ToLower(v["serverLocation"])

	// extract appID and appKey as BASIC auth.
	u, p, ok := r.BasicAuth()
	if !ok {
		return ErrNoAuthorization
	}
	if u == "" || p == "" {
		return ErrInvalidGrant
	}
	op.appID, op.appKey = u, p

	m, err := jp.parseJSON(r)
	if err != nil {
		return newInvalidUsernamePassword(err)
	}
	x := dproxy.New(m)
	op.username, err = x.M("username").String()
	if err != nil {
		return newInvalidUsernamePassword(err)
	}
	op.password, err = x.M("password").String()
	if err != nil {
		return newInvalidUsernamePassword(err)
	}
	return nil
}
Ejemplo n.º 3
0
func (as *AuthServer) ParseRequest(req *http.Request) (*AuthRequest, error) {
	ar := &AuthRequest{RemoteAddr: req.RemoteAddr, Actions: []string{}}
	user, password, haveBasicAuth := req.BasicAuth()
	if haveBasicAuth {
		ar.User = user
		ar.Password = authn.PasswordString(password)
	}
	ar.Account = req.FormValue("account")
	if ar.Account == "" {
		ar.Account = ar.User
	} else if haveBasicAuth && ar.Account != ar.User {
		return nil, fmt.Errorf("user and account are not the same (%q vs %q)", ar.User, ar.Account)
	}
	ar.Service = req.FormValue("service")
	scope := req.FormValue("scope")
	if scope != "" {
		parts := strings.Split(scope, ":")
		if len(parts) != 3 {
			return nil, fmt.Errorf("invalid scope: %q", scope)
		}
		ar.Type = parts[0]
		ar.Name = parts[1]
		ar.Actions = strings.Split(parts[2], ",")
		sort.Strings(ar.Actions)
	}
	return ar, nil
}
Ejemplo n.º 4
0
func (b *basicauth) ServeHTTP(w http.ResponseWriter, r *http.Request) {

	// don't request passwords for the websocket interface (for now)
	// because 'wscat' doesn't support that.
	if r.RequestURI == "/monitor" {
		b.h.ServeHTTP(w, r)
		return
	}

	cfgMutex.RLock()
	user := Config.HTTP.User
	password := Config.HTTP.Password
	cfgMutex.RUnlock()

	if len(user) == 0 {
		b.h.ServeHTTP(w, r)
		return
	}

	ruser, rpass, ok := r.BasicAuth()
	if ok {
		if ruser == user && rpass == password {
			b.h.ServeHTTP(w, r)
			return
		}
	}

	w.Header().Set("WWW-Authenticate", fmt.Sprintf(`Basic realm=%q`, "GeoDNS Status"))
	http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
	return
}
Ejemplo n.º 5
0
// parseCredentials parses a request and returns the authentication credentials.
// The credentials may be present as URL query params, or as a Basic
// Authentication header.
// As params: http://127.0.0.1/query?u=username&p=password
// As basic auth: http://username:[email protected]
// As Bearer token in Authorization header: Bearer <JWT_TOKEN_BLOB>
func parseCredentials(r *http.Request) (*credentials, error) {
	q := r.URL.Query()

	// Check for the HTTP Authorization header.
	if s := r.Header.Get("Authorization"); s != "" {
		// Check for Bearer token.
		strs := strings.Split(s, " ")
		if len(strs) == 2 && strs[0] == "Bearer" {
			return &credentials{
				Method: BearerAuthentication,
				Token:  strs[1],
			}, nil
		}

		// Check for basic auth.
		if u, p, ok := r.BasicAuth(); ok {
			return &credentials{
				Method:   UserAuthentication,
				Username: u,
				Password: p,
			}, nil
		}
	}

	// Check for username and password in URL params.
	if u, p := q.Get("u"), q.Get("p"); u != "" && p != "" {
		return &credentials{
			Method:   UserAuthentication,
			Username: u,
			Password: p,
		}, nil
	}

	return nil, fmt.Errorf("unable to parse authentication credentials")
}
Ejemplo n.º 6
0
func (hli *HttpListenInput) RequestHandler(w http.ResponseWriter, req *http.Request) {
	var err error

	if hli.conf.AuthType == "Basic" {
		if hli.conf.Username != "" && hli.conf.Password != "" {
			user, pass, ok := req.BasicAuth()
			if !ok || user != hli.conf.Username || pass != hli.conf.Password {
				err = fmt.Errorf("Basic Auth Failed")
				hli.ir.LogError(err)
			}
		}
	}
	if hli.conf.AuthType == "API" {
		if hli.conf.Key != "" {
			api_key := req.Header.Get("X-API-Key")
			if api_key != hli.conf.Key {
				err = fmt.Errorf("API Auth Failed")
				hli.ir.LogError(err)
			}
		}
	}
	if err == nil {
		sRunner := hli.ir.NewSplitterRunner(req.RemoteAddr)
		if !sRunner.UseMsgBytes() {
			sRunner.SetPackDecorator(hli.makePackDecorator(req))
		}
		err = sRunner.SplitStreamNullSplitterToEOF(req.Body, nil)
		if err != nil && err != io.EOF {
			hli.ir.LogError(fmt.Errorf("receiving request body: %s", err.Error()))
		}
		req.Body.Close()
		sRunner.Done()
	}
}
Ejemplo n.º 7
0
// HTTP handler to decode request body and hand off to
// vendor-specific reporters
// This is where we could fan out to multiple reporters
// or detect reporters based on ENV vars
func reportError(w http.ResponseWriter, r *http.Request) {
	// basic auth
	_, password, ok := r.BasicAuth()
	passwordOk := (password == os.Getenv("PASSWORD1") || password == os.Getenv("PASSWORD2"))
	if !(ok && passwordOk) {
		w.Header().Set("WWW-Authenticate", `Basic realm="Errors"`)
		w.WriteHeader(401)
		w.Write([]byte("unauthorized"))
		return
	}

	// decode request body into ErrorPost
	var errorPost ErrorPost
	decoder := json.NewDecoder(r.Body)
	err := decoder.Decode(&errorPost)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	// report errors
	reportToRollbar(errorPost)

	// all ok
	w.Write([]byte("ok"))
}
Ejemplo n.º 8
0
// FromRequest inspects the HTTP Authorization header of the given request
// and tries to identify a passenger.
func FromRequest(ctx context.Context, r *http.Request) (*Passenger, error) {
	cookie, err := r.Cookie("token")
	if err != nil && err != http.ErrNoCookie {
		return nil, err
	}
	if err == nil {
		return FromToken(ctx, cookie.Value)
	}

	auth := ""
	if auth = r.Header.Get("Authorization"); auth == "" {
		return nil, ErrNoAuthHeader
	}

	if strings.HasPrefix(auth, "Token ") {
		return FromToken(ctx, auth[6:])
	}

	username, password, ok := "", "", false
	if username, password, ok = r.BasicAuth(); !ok {
		return nil, ErrUnkAuthHeader
	}

	return FromBasicAuth(ctx, username, password)
}
Ejemplo n.º 9
0
// authenticator reads the username from the HTTP basic authentication header
// and validates the token. It sets the "user" key in the context to the
// user associated with the token.
func authenticator(c siesta.Context, w http.ResponseWriter, r *http.Request,
	quit func()) {
	// Context variables
	requestID := c.Get("request-id").(string)
	db := c.Get("db").(*DB)

	// Check for a token in the HTTP basic authentication username field.
	token, _, ok := r.BasicAuth()
	if ok {
		user, err := db.validateToken(token)
		if err != nil {
			log.Printf("[Req %s] Did not provide a valid token", requestID)
			c.Set("status-code", http.StatusUnauthorized)
			c.Set("error", "invalid token")
			quit()
			return
		}

		log.Printf("[Req %s] Provided a token for: %s", requestID, user)

		// Add the user to the context.
		c.Set("user", user)
	} else {
		log.Printf("[Req %s] Did not provide a token", requestID)

		c.Set("error", "token required")
		c.Set("status-code", http.StatusUnauthorized)

		// Exit the chain here.
		quit()
		return
	}
}
Ejemplo n.º 10
0
// IssueToken handles all requests going to tokens endpoint.
func IssueToken(w http.ResponseWriter, req *http.Request, cfg config) {
	provider := cfg.provider
	username, password, ok := req.BasicAuth()
	cinfo, err := provider.AuthenticateClient(username, password)
	if !ok || err != nil {
		render.JSON(w, render.Options{
			Status: http.StatusBadRequest,
			Data:   ErrUnauthorizedClient,
		})
		return
	}

	grantType := req.FormValue("grant_type")
	switch grantType {
	case "authorization_code":
		authCodeGrant2(w, req, cfg, cinfo)
	case "client_credentials":
		clientCredentialsGrant(w, req, cfg, cinfo)
	case "password":
		resourceOwnerCredentialsGrant(w, req, cfg, cinfo)
	case "refresh_token":
		refreshToken(w, req, cfg, cinfo)
	default:
		render.JSON(w, render.Options{
			Status: http.StatusBadRequest,
			Data:   ErrUnsupportedGrantType,
		})
		return
	}
}
Ejemplo n.º 11
0
func collect(w http.ResponseWriter, r *http.Request) {
	username, password, ok := r.BasicAuth()
	if ok {
		_ = fmt.Sprintf("Username: %s | Password: %s", username, password)
		body, err := ioutil.ReadAll(r.Body)
		if err != nil {
			log.Fatal(err)
		}
		mxj.XmlCharsetReader = charset.NewReader
		m, err := mxj.NewMapXml(body) // unmarshal
		if err != nil {
			log.Fatal(err)
		}
		// Single path
		path := m.PathForKeyShortest("avg01")
		val, err := m.ValueForPath(path)
		if err != nil {
			log.Fatal(err)
		}
		fmt.Println(val)
		// Multi-path
		paths := m.PathsForKey("percent")
		for _, path := range paths {
			val, err := m.ValueForPath(path)
			if err != nil {
				log.Fatal(err)
			}
			fmt.Println(val)
		}
		io.WriteString(w, "Success")
	}
}
Ejemplo n.º 12
0
func (as *AuthServer) ParseRequest(req *http.Request) (*AuthRequest, error) {
	ar := &AuthRequest{RemoteAddr: req.RemoteAddr}
	ar.ai.IP = parseRemoteAddr(req.RemoteAddr)
	if ar.ai.IP == nil {
		return nil, fmt.Errorf("unable to parse remote addr %s", req.RemoteAddr)
	}
	user, password, haveBasicAuth := req.BasicAuth()
	glog.V(3).Infof("user : %s, password : %s, haveBasicAuth : %v", user, password, haveBasicAuth)
	if haveBasicAuth {
		ar.User = user
		ar.Password = authn.PasswordString(password)
	}
	ar.ai.Account = req.FormValue("account")
	if ar.ai.Account == "" {
		ar.ai.Account = ar.User
	} else if haveBasicAuth && ar.ai.Account != ar.User {
		return nil, fmt.Errorf("user and account are not the same (%q vs %q)", ar.User, ar.ai.Account)
	}
	ar.ai.Service = req.FormValue("service")
	scope := req.FormValue("scope")
	if scope != "" {
		parts := strings.Split(scope, ":")
		if len(parts) != 3 {
			return nil, fmt.Errorf("invalid scope: %q", scope)
		}
		ar.ai.Type = parts[0]
		ar.ai.Name = parts[1]
		ar.ai.Actions = strings.Split(parts[2], ",")
		sort.Strings(ar.ai.Actions)
		glog.V(3).Infof("scope Type : %s, Name : %s, Actions : %s", ar.ai.Type, ar.ai.Name, ar.ai.Actions)
	}
	glog.V(3).Infoln("AuthServer :", ar)
	return ar, nil
}
Ejemplo n.º 13
0
func (s *service) getBasicAuthCredentials(r *http.Request) (email, username, password string) {
	if un, pw, ok := r.BasicAuth(); !ok {
		panic(s.ErrorsService.CreateHttpStatusClientError_Unauthorized("Unable to extract basic auth credentials"))
	} else {
		return un, un, pw
	}
}
Ejemplo n.º 14
0
func homePage(writer http.ResponseWriter, request *http.Request) {
	name, _, successAuth := request.BasicAuth()
	if !successAuth {
		writer.Header().Set("WWW-Authenticate", `Basic realm="protectedpage"`)
		http.Error(writer, "bad auth", http.StatusUnauthorized)
		return
	}
	writer.Header().Set("Content-type", "text/html")
	userPath := "cloud/usersStorage/" + name
	err := os.MkdirAll(userPath, 0777)
	if err != nil {
		log.Println(err, "problem with creating user's directory")
		http.Error(writer, "problen with user path", http.StatusBadRequest)
	}

	if reqSend := request.FormValue("sendButton"); reqSend != "" {
		uploadFile(request, userPath)
		showEntireFolder(writer, request, userPath, templt, name)
		return
	}
	if reqSend := request.FormValue("deleteButton"); reqSend != "" {
		slice, found := request.Form["option"]
		for i, _ := range slice {
			if err = deleteFile(slice[i], userPath); err != nil && found {
				http.Error(writer, "problem with deleting", http.StatusBadRequest)
			}
		}
		showEntireFolder(writer, request, userPath, templt, name)
		return
	}
	showEntireFolder(writer, request, userPath, templt, name)
}
Ejemplo n.º 15
0
// ServeHTTP allows Service to serve HTTP requests.
func (s *Service) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if s.credentialStore != nil {
		username, password, ok := r.BasicAuth()
		if !ok || !s.credentialStore.Check(username, password) {
			w.WriteHeader(http.StatusUnauthorized)
			return
		}
	}

	switch {
	case strings.HasPrefix(r.URL.Path, "/db/execute"):
		stats.Add(numExecutions, 1)
		s.handleExecute(w, r)
	case strings.HasPrefix(r.URL.Path, "/db/query"):
		stats.Add(numQueries, 1)
		s.handleQuery(w, r)
	case strings.HasPrefix(r.URL.Path, "/db/backup"):
		stats.Add(numBackups, 1)
		s.handleBackup(w, r)
	case strings.HasPrefix(r.URL.Path, "/join"):
		s.handleJoin(w, r)
	case strings.HasPrefix(r.URL.Path, "/status"):
		s.handleStatus(w, r)
	case r.URL.Path == "/debug/vars" && s.Expvar:
		serveExpvar(w, r)
	default:
		w.WriteHeader(http.StatusNotFound)
	}
}
func NotFoundHandler(w http.ResponseWriter, r *http.Request) {
	// If HTTP Method is OPTIONS, return CORS
	if r.Method == "OPTIONS" {
		w.Header().Set("Access-Control-Allow-Origin", "*")
		w.Header().Set("Access-Control-Allow-Headers", "Authorization,DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type")
		w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
		w.Header().Set("Access-Control-Allow-Credentials", "true")
		w.Header().Set("Access-Control-Max-Age", "1728000")
		w.Header().Set("Content-Type", "text/plain charset=UTF-8")
		w.Header().Set("Content-Length", "0")
		l.Info("OPTIONS")
		return
	}

	// If header "Authorization" is not null and invalid, return 403
	if r.Header.Get("Authorization") != "" {
		u, p, ok := r.BasicAuth()
		if ok == true && u == DGConfig.DockerGuard.API.APILogin && p == DGConfig.DockerGuard.API.APIPassword {
			http.Error(w, http.StatusText(404), 404)
			return
		}
		http.Error(w, http.StatusText(403), 403)
	} else {
		http.Error(w, http.StatusText(404), 404)
	}
}
Ejemplo n.º 17
0
func hasRootAccess(sec auth.Store, r *http.Request) bool {
	if sec == nil {
		// No store means no auth available, eg, tests.
		return true
	}
	if !sec.AuthEnabled() {
		return true
	}
	username, password, ok := r.BasicAuth()
	if !ok {
		return false
	}
	rootUser, err := sec.GetUser(username)
	if err != nil {
		return false
	}
	ok = rootUser.CheckPassword(password)
	if !ok {
		plog.Warningf("auth: wrong password for user %s", username)
		return false
	}
	for _, role := range rootUser.Roles {
		if role == auth.RootRoleName {
			return true
		}
	}
	plog.Warningf("auth: user %s does not have the %s role for resource %s.", username, auth.RootRoleName, r.URL.Path)
	return false
}
Ejemplo n.º 18
0
/* web pages */
func (m *Notify) JIDPage(w http.ResponseWriter, r *http.Request) {
	if !m.isIpAllowed(r) {
		http.NotFound(w, r)
		return
	}
	if username, password, ok := r.BasicAuth(); !ok {
		w.Header().Set("WWW-Authenticate", "Basic realm=\"xmppbot\"")
		http.Error(w, http.StatusText(401), 401)
		return
	} else if !(m.Option["authuser"] == username && m.Option["authpass"] == password) {
		w.Header().Set("WWW-Authenticate", "Basic realm=\"xmppbot\"")
		http.Error(w, http.StatusText(401), 401)
		return
	}

	if strings.ToLower(r.Method) != "post" {
		http.NotFound(w, r)
		return
	}
	vars := mux.Vars(r)
	jid := vars["jid"]
	if m.bot.IsRoomID(jid) {
		m.bot.SendPub(jid, fmt.Sprintf("通知:%s\n%s", r.FormValue("subject"), r.FormValue("body")))
	} else {
		m.bot.SendAuto(jid, fmt.Sprintf("通知:%s\n%s", r.FormValue("subject"), r.FormValue("body")))
	}
	w.Write([]byte("notify sent to " + jid + "\n"))
}
Ejemplo n.º 19
0
func (h tokenHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	// TODO: actually check the basic auth values
	_, _, ok := req.BasicAuth()
	if !ok {
		common.Error(w, http.StatusUnauthorized, "An Authentication object was not found in the SecurityContext", "unauthorized")
		return
	}

	err := req.ParseForm()
	if err != nil {
		panic(err)
	}
	clientID := req.Form.Get("client_id")

	scopes := []string{"scim.write", "scim.read", "password.write"}
	t := domain.Token{
		ClientID:  clientID,
		Scopes:    scopes,
		Audiences: []string{"scim", "password"},
	}

	response, err := json.Marshal(t.ToDocument())
	if err != nil {
		panic(err)
	}

	w.Write(response)
}
Ejemplo n.º 20
0
func (t TabAuth) isAuthenticated(r *http.Request) bool {
	username, password, ok := r.BasicAuth()
	if ok && password == t.accounts[username] {
		return true
	}
	return false
}
Ejemplo n.º 21
0
func parseRequest(req *http.Request) (*AuthRequest, error) {
	service, err := getService(req)
	if err != nil {
		return nil, err
	}

	account := req.FormValue("account")

	scopes, err := getScopes(req)
	if err != nil {
		return nil, err
	}

	user, pass, haveAuth := req.BasicAuth()
	if haveAuth {
		if account != "" && user != account {
			return nil, HTTPBadRequest("authorization failue. account and user passed are different.")
		}
		account = user
	}

	return &AuthRequest{
		Service:  service,
		Account:  account,
		Password: pass,
		Scope:    scopes,
	}, nil
}
Ejemplo n.º 22
0
func requestAuthKey(req *http.Request) string {
	authKey, _, ok := req.BasicAuth()
	if ok {
		return authKey
	}
	return req.FormValue("apikey")
}
Ejemplo n.º 23
0
// authHandler is called in a goroutine to handle each incoming request
func authHandler(w http.ResponseWriter, r *http.Request) {

	// pull the auth details from the request
	user, pass, ok := r.BasicAuth()
	if ok == true {

		host, _, err := net.SplitHostPort(r.RemoteAddr)
		if err != nil {
			host = ""
		}
		r := &AuthEvent{
			Time:        fmt.Sprintf("%d", time.Now().Unix()),
			AuthType:    "httpAuth",
			SrcIP:       host,
			DestIP:      extIP,
			User:        user,
			Credentials: strconv.QuoteToASCII(pass),
		}
		addToBatch(r)

	}
	// always return auth fail
	w.Header().Set("WWW-Authenticate", "Basic realm=Restricted")
	http.Error(w, "authorization failed", http.StatusUnauthorized)
}
Ejemplo n.º 24
0
Archivo: auth.go Proyecto: ssoor/webapi
func (this Middleware) OnRequest(req *http.Request, writer *http.ResponseWriter) *http.ResponseWriter {
	var authenticated bool
	username, password, ok := req.BasicAuth()
	if ok {
		if len(username) > 0 {
			if v, ok := this.credentials[username]; ok {
				if Equal(v, password) {
					authenticated = true
				}
			}

			if !authenticated && this.AuthenticationFunc != nil {
				authenticated = this.AuthenticationFunc(username, password)
			}
		}
	}

	if !authenticated {
		writer.Write(http.StatusUnauthorized)
		writer.Header().Set("WWW-Authenticate", "Basic realm=\"Authorization Required\"")
	} else {
		// set username in the context, the username can be read later using context.Data[authentication.AuthenticatedUsername]
		context.Data[AuthenticatedUsername] = username
	}
}
Ejemplo n.º 25
0
func getOpenShiftAPIToken(ctx context.Context, req *http.Request) (string, error) {
	token := ""

	authParts := strings.SplitN(req.Header.Get("Authorization"), " ", 2)
	if len(authParts) != 2 {
		return "", ErrTokenRequired
	}

	switch strings.ToLower(authParts[0]) {
	case "bearer":
		// This is either a direct API token, or a token issued by our docker token handler
		token = authParts[1]
		// Recognize the token issued to anonymous users by our docker token handler
		if token == anonymousToken {
			token = ""
		}

	case "basic":
		_, password, ok := req.BasicAuth()
		if !ok || len(password) == 0 {
			return "", ErrTokenInvalid
		}
		token = password

	default:
		return "", ErrTokenRequired
	}

	return token, nil
}
Ejemplo n.º 26
0
func (s *UAAServer) OAuthToken(w http.ResponseWriter, req *http.Request) {
	_, _, ok := req.BasicAuth()
	if !ok {
		s.Error(w, http.StatusUnauthorized, "An Authentication object was not found in the SecurityContext", "unauthorized")
		return
	}

	err := req.ParseForm()
	if err != nil {
		panic(err)
	}
	clientID := req.Form.Get("client_id")

	scopes := []string{"scim.write", "scim.read", "password.write"}
	token := s.tokenizer.Encrypt(Token{
		ClientID:  clientID,
		Scopes:    scopes,
		Audiences: []string{"scim", "password"},
	})

	response, err := json.Marshal(documents.TokenResponse{
		AccessToken: token,
		TokenType:   "bearer",
		ExpiresIn:   5000,
		Scope:       strings.Join(scopes, " "),
		JTI:         GenerateID(),
	})

	w.Write(response)
}
Ejemplo n.º 27
0
// parses the username either from the url or auth header
func parseUsername(r *http.Request) string {
	var (
		username = ""
		url      = r.URL
	)

	// get username from the url if passed there
	if url.User != nil {
		if name := url.User.Username(); name != "" {
			username = name
		}
	}

	// Try to get the username from the query param 'u'
	q := url.Query()
	if u := q.Get("u"); u != "" {
		username = u
	}

	// Try to get it from the authorization header if set there
	if username == "" {
		if u, _, ok := r.BasicAuth(); ok {
			username = u
		}
	}
	return username
}
Ejemplo n.º 28
0
// 認証チェック
func checkAuth(r *http.Request) bool {
	username, password, ok := r.BasicAuth()
	if ok == false {
		return false
	}
	return username == commandUserId && password == commandPassword
}
Ejemplo n.º 29
0
func (a *BasicAuth) ValidAuth(r *http.Request) bool {
	username, password, ok := r.BasicAuth()
	if !ok {
		return false
	}
	return username == a.Login && password == a.Password
}
Ejemplo n.º 30
0
// See if user is in the system, if yes assign a session ID to him
func UserAuthLoginHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	username, password, ok := r.BasicAuth()
	if !ok {
		w.WriteHeader(http.StatusUnauthorized)
		return
	}

	userID, _, ok := UserAuth(username, password)
	if !ok {
		w.WriteHeader(http.StatusUnauthorized)
		return
	}

	// creating session
	sessionID := utils.RandomSHA1()
	var err error
	for tries := 0; tries < 3; tries++ {
		_, err = MyDB.connection.Exec("insert into usersessions(sessionkey, user_id) values($1,$2)",
			sessionID, userID)

		if err == nil {
			break
		}
	}
	if err != nil {
		panic(err)
	}

	// Set output
	c := http.Cookie{Name: "sessionId", Value: sessionID}
	http.SetCookie(w, &c)

	log.Info("Login successful for user:%s user_id:%d", username, userID)
}