Skip to content

Instantly share code, notes, and snippets.

View collinvandyck's full-sized avatar
🏠
Working from home

Collin Van Dyck collinvandyck

🏠
Working from home
View GitHub Profile
@Path("authenticate")
@Produces(MediaType.APPLICATION_JSON)
public class AuthResource {
private final UserDAO userDAO;
public AuthResource(UserDAO userDAO) {
this.userDAO = userDAO;
}
@GET
func main() {
http.HandleFunc("/authenticate", Authenticate)
http.ListenAndServe(":8080", nil)
}
type Credentials string
func Authenticate(w http.ResponseWriter, r *http.Request) {
credentials, err := newCredentials(r)
if err != nil {
http.Error(w, err.Error(), BadRequest)
return
}
user, err := GetUserByApiKey(db, credentials)
if err != nil {
public interface UserDAO {
@SqlQuery("SELECT u.id, u.email, u.password_hash, u.apikey, u.created_at, u.updated_at, u.name, u.id, u.admin, u.active from users u where u.apikey = :apiKey")
@RegisterMapper(UserMapper.class)
User getUserByApiKey(@Bind("apiKey") String apiKey);
static class UserMapper implements ResultSetMapper<User> {
@Override
public User map(int i, ResultSet rs, StatementContext statementContext) throws SQLException {
return new User(
type User struct {
Id string `json:"id"`
Email string `json:"email,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Name string `json:"name,omitempty"`
Admin bool `json:"admin"`
Active bool `json:"-"`
}
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public class User {
private static final DateFormat ISO_8601_FORMATTER = new ISO8601DateFormat();
public static String dateToISO8601Format(Date date) {
if (date == null) {
return null;
}
return ISO_8601_FORMATTER.format(date);
}
bytes, err := json.Marshal(user)
if err != nil {
http.Error(w, err.Error(), Unauthorized)
return
}
w.Write(bytes)
type User struct {
Id string `json:"id"`
Email string `json:"email,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Name string `json:"name,omitempty"`
Admin bool `json:"admin"`
Active bool `json:"-"`
}
public class AuthService extends Service<AuthConfiguration> {
// methods elided
@Override
protected void initialize(AuthConfiguration config, Environment environment) throws Exception {
final DatabaseFactory factory = new DatabaseFactory(environment);
final Database db = factory.build(config.getDatabaseConfiguration(), "postgresql");
final UserDAO userDAO = db.onDemand(UserDAO.class);
func getDecodedAuthorizationHeader(headers http.Header) (aType string, aValue string, err error) {
auth := strings.Split(headers.Get("Authorization"), " ")
if len(auth) != 2 {
return aType, aValue, errors.New("Bad auth header")
}
if auth[0] == "Basic" {
reader := base64.NewDecoder(base64.StdEncoding, strings.NewReader(auth[1]))
bytes, err := ioutil.ReadAll(reader)
if err != nil {
return aType, aValue, err