Page Menu
Home
Musing Studio
Search
Configure Global Search
Log In
Files
F10384312
auth.go
No One
Temporary
Actions
View File
Edit File
Delete File
View Transforms
Subscribe
Mute Notifications
Award Token
Flag For Later
Size
1 KB
Subscribers
None
auth.go
View Options
package
writeas
import
(
"context"
"fmt"
"net/http"
)
// LogIn authenticates a user with Write.as.
// See https://developers.write.as/docs/api/#authenticate-a-user
func
(
c
*
Client
)
LogIn
(
ctx
context
.
Context
,
username
,
pass
string
)
(
*
AuthUser
,
error
)
{
u
:=
&
AuthUser
{}
up
:=
struct
{
Alias
string
`json:"alias"`
Pass
string
`json:"pass"`
}{
Alias
:
username
,
Pass
:
pass
,
}
env
,
err
:=
c
.
post
(
ctx
,
"/auth/login"
,
up
,
u
)
if
err
!=
nil
{
return
nil
,
err
}
var
ok
bool
if
u
,
ok
=
env
.
Data
.(
*
AuthUser
);
!
ok
{
return
nil
,
fmt
.
Errorf
(
"Wrong data returned from API."
)
}
status
:=
env
.
Code
if
status
!=
http
.
StatusOK
{
if
status
==
http
.
StatusBadRequest
{
return
nil
,
fmt
.
Errorf
(
"Bad request: %s"
,
env
.
ErrorMessage
)
}
else
if
status
==
http
.
StatusUnauthorized
{
return
nil
,
fmt
.
Errorf
(
"Incorrect password."
)
}
else
if
status
==
http
.
StatusNotFound
{
return
nil
,
fmt
.
Errorf
(
"User does not exist."
)
}
else
if
status
==
http
.
StatusTooManyRequests
{
return
nil
,
fmt
.
Errorf
(
"Too many log in attempts in a short period of time."
)
}
return
nil
,
fmt
.
Errorf
(
"Problem authenticating: %d. %v\n"
,
status
,
err
)
}
c
.
SetToken
(
u
.
AccessToken
)
return
u
,
nil
}
// LogOut logs the current user out, making the Client's current access token
// invalid.
func
(
c
*
Client
)
LogOut
(
ctx
context
.
Context
)
error
{
env
,
err
:=
c
.
delete
(
ctx
,
"/auth/me"
,
nil
)
if
err
!=
nil
{
return
err
}
status
:=
env
.
Code
if
status
!=
http
.
StatusNoContent
{
if
status
==
http
.
StatusNotFound
{
return
fmt
.
Errorf
(
"Access token is invalid or doesn't exist"
)
}
return
fmt
.
Errorf
(
"Unable to log out: %v"
,
env
.
ErrorMessage
)
}
// Logout successful, so update the Client
c
.
token
=
""
return
nil
}
func
(
c
*
Client
)
isNotLoggedIn
(
code
int
)
bool
{
if
c
.
token
==
""
{
return
false
}
return
code
==
http
.
StatusUnauthorized
}
File Metadata
Details
Attached
Mime Type
text/plain
Expires
Sat, Nov 23, 11:03 AM (1 d, 6 h)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
3104527
Attached To
rWGO writeas-go
Event Timeline
Log In to Comment