Mail functionality using OPA - email

import stdlib.web.mail
from = {name="name" address={local="username" domain="gmail.com"}}
to = {name="name" address={local="username" domain="gmail.com"}}
r = Email.try_send(from, to, "Subject", {text = "This is Great!"})
server = Server.one_page_server("Mail", [], [], r)
the following error I'm getting
Error
File "mail.opa", line 6, characters 4-66, (6:4-6:66 | 166-228)
Function was found of type
Email.email, Email.email, string, Email.content -> Email.send_status but
application expects it to be of type
{ address: { domain: string; local: string } / 'c.b; name: string } / 'c.a,
{ address: { domain: string; local: string } / 'c.d; name: string } / 'c.c,
string, { text: string } / 'c.e -> 'a.
Types string and { none } / { some: string } are not compatible
Hint:
Error occurred through field name.
Can anyone help me with Mail functionality in Opa?

There is a number of problems with this code:
Notice that in Email.email type the name field is optional; so if you want to include it you should provide some("name"), not just "name"
Server.one_page_server contains 2 arguments not 4.
The last argument to one_page_server should be the xhtml of the page, whereas your r is the result of sending an email.
After those fixes your code could look something like this:
import stdlib.web.mail
from = {name=some("name") address={local="username" domain="gmail.com"}} : Email.email
to = {name=some("name") address={local="username" domain="gmail.com"}} : Email.email
page() =
status = Email.try_send(from, to, "Subject", {text = "This is Great!"})
<>Email sent</>
server = Server.one_page_server("Mail", page)

Related

Tags format on Packer ec2-ami deployment

I'm trying out to create an amazon ec2 ami for the 1st time using Hashicorp Packer, however getting this failure on the tag creation, I already tried some retries on trial and error test for the format but still unlucky
[ec2-boy-oh-boy#ip-172-168-99-23 pogi]$ packer init .
Error: Missing item separator
on variables.pkr.hcl line 28, in variable "tags":
27: default = [
28: "environment" : "testing"
Expected a comma to mark the beginning of the next item.
My code ec2.pkr.hcl looks like this:
[ec2-boy-oh-boy#ip-172-168-99-23 pogi]$ cat ec2.pkr.hcl
packer {
required_plugins {
amazon = {
version = ">= 0.0.2"
source = "github.com/hashicorp/amazon"
}
}
}
source "amazon-ebs" "ec2" {
ami_name = "${var.ami_prefix}-${local.timestamp}"
instance_type = "t2.micro"
region = "us-east-1"
vpc_id = "${var.vpc}"
subnet_id = "${var.subnet}"
security_group_ids = ["${var.sg}"]
ssh_username = "ec2-boy-oh-boy"
source_ami_filter {
filters = {
name = "amzn2-ami-hvm-2.0*"
root-device-type = "ebs"
virtualization-type = "hvm"
}
most_recent = true
owners = ["12345567896"]
}
launch_block_device_mappings = [
{
"device_name": "/dev/xvda",
"delete_on_termination": true
"volume_size": 10
"volume_type": "gp2"
}
]
run_tags = "${var.tags}"
run_volume_tags = "${var.tags}"
}
build {
sources = [
"source.amazon-ebs.ec2"
]
}
[ec2-boy-oh-boy#ip-172-168-99-23 pogi]$
Then my code variables.pkr.hcl looks like this:
[ec2-boy-oh-boy#ip-172-168-99-23 pogi]$ cat variables.pkr.hcl
locals {
timestamp = regex_replace(timestamp(), "[- TZ:]", "")
}
variable "ami_prefix" {
type = string
default = "ec2-boy-oh-boy"
}
variable "vpc" {
type = string
default = "vpc-asd957d"
}
variable "subnet" {
type = string
default = "subnet-asd957d"
}
variable "sg" {
type = string
default = "sg-asd957d"
}
variable "tags" {
type = map
default = [
environment = "testing"
type = "none"
production = "later"
]
}
Your default value for the tags variable is of type list(string). Both the run_tags and run_volume_tags directives expect type map[string]string.
I was able to make the following changes to your variables file and run packer init successfully:
variable "tags" {
default = {
environment = "testing"
type = "none"
production = "later"
}
type = map(string)
}

django rest framework - return custom data for a model serializer field

I have the following model:
class ServerSimpleConfigSerializer(mixins.GetCSConfigMixin, serializers.ModelSerializer):
mp_autoteambalance = serializers.BooleanField(label='Auto Team Balance', default=True, required=False)
mp_friendlyfire = serializers.BooleanField(label='Friendly Fire', default=False, required=False)
mp_autokick = serializers.BooleanField(label='Auto team-killer banning and idle client kicking', default=True, required=False)
# hostname = serializers.CharField(label='Hostname', max_length=75, required=True)
rcon_password = serializers.CharField(label='RCON Password', max_length=75, required=True)
sv_password = serializers.CharField(label='Server Password', max_length=75, required=False)
mp_startmoney = serializers.IntegerField(label='Start Money', required=False, validators=[MinValueValidator(800), MaxValueValidator(16000)])
mp_roundtime = serializers.FloatField(label='Round Time', required=False)
mp_timelimit = serializers.IntegerField(label='Map Time Limit', required=False)
fpath = os.path.join(settings.ROOT_DIR, "cs16/tmp/server.json")
class Meta:
model = CS16Server
fields = ('name', 'game_config', 'mp_autoteambalance', 'mp_friendlyfire',
'mp_autokick', 'hostname', 'rcon_password', 'sv_password',
'mp_startmoney', 'mp_roundtime', 'mp_timelimit')
read_only_fields = ('name', 'game_config',)
The model has the following fields:
name, game_config (big text) and hostname
How can I return the above defined fields for the serializer, although they are not present on the model ?
I would like to set some custom values for each field & return them as a JSON.
Is that possible ?
Actually the values for the above defined fields are found in "game_config" field.
I would like to parse those values & return them & I would not want to put them as separate fields in the model.
Parse game_config, obtain a pair of: (field0, val0) ... (fieldN, valN) and in the serializer,
set those values for the serializer fields.
For now I only get the following response:
{
"name": "Chronos",
"game_config": "hostname \"A New Gameservers.com Server is Born\"\nrcon_password \"\"\nsv_password \"1410271\"\nsv_contact email#domain.com\nsv_region 255\nsv_filterban 1\nsv_logbans 0\nsv_unlag 1\nmp_startmoney 800\nmp_chattime 30\nmp_footsteps 1\nsv_footsteps 1\nmp_logdetail 0\nmp_logmessages 0\nmp_timelimit 30\nmp_autokick 1\nmp_autoteambalance 1\nmp_flashlight 0\nmp_forcerespawn 0\nmp_forcechasecam 0\nmp_freezetime 0\nmp_friendlyfire 0\nmp_hostagepenalty 0\nmp_limitteams 0\nmp_roundtime 5\nmp_tkpunish 1\nsv_voiceenable 1\nsv_voicecodec voice_speex\nsv_voicequality 3\nsv_alltalk 0\nsv_restartround 1\nsv_maxspeed 320\nsv_proxies 1\nallow_spectators 1\nsv_allowupload 1\npausable 0\ndecalfrequency 40\nmp_falldamage 0\nsv_cheats 0\nsv_lan 0\nsv_maxrate 20000\nsv_minrate 4000\nexec listip.cfg",
"mp_autoteambalance": true,
"mp_friendlyfire": false,
"mp_autokick": true,
"hostname": "none"
}

Unable to parse module: unexpected = expecting indentation at column 1 or end of input

Wrote this code
module Main where
import Prelude
import Data.List (List)
import Control.Monad.Eff (Eff)
import Control.Monad.Eff.Console (CONSOLE, log)
type Entry = {
firstName :: String,
lastName :: String,
address :: Address
}
type Address = {
street :: String,
city :: String,
state :: String
}
type AddressBook = List Entry
showEntry :: Entry -> String
showEntry entry = entry.lastName <> ", " <>
entry.firstName <> ", " <>
showAddress entry.address
showAddress :: Address -> String
showAddress address = address.street <> ", " <>
address.city <> ", " <>
address.state
main :: forall e. Eff (console :: CONSOLE | e) Unit
main = do
log "Hello Sailor!"
address = {street: "123 Fake St.", city: "Faketown", state: "CA"}
showAddress address
everything is indented with two spaces
I get error
Error found:
at src/Main.purs line 34, column 11 - line 34, column 11
Unable to parse module:
unexpected =
expecting indentation at column 1 or end of input
See https://github.com/purescript/documentation/blob/master/errors/ErrorParsingModule.md for more information,
or to contribute content related to this error.
I also tried
main = do
log "Hello Sailor!"
address :: Address
address = {street: "123 Fake St.", city: "Faketown", state: "CA"}
showAddress address
but still get the same error.
You can't have out-of-the-blue bindings within a do notation, or indeed anywhere except top-level.
If you want to name an intermediate value, you have to use let:
main = do
log "Hello Sailor!"
let address = {street: "123 Fake St.", city: "Faketown", state: "CA"}
showAddress address
In your case, since address doesn't depend on the previous code, you can also bind it with where:
main = do
log "Hello Sailor!"
showAddress address
where
address = {street: "123 Fake St.", city: "Faketown", state: "CA"}
And even at top level, you can't have bindings that just stand on their own. See that where at the very top after module Main? That means everything inside this module is where-bound.
So the correct statement would be this: bindings can never stand on their own, they always have to be either let- or where-bound.
Also note: you can have multiple bindings inside a single let or a single where:
f x = do
let y = a + 42
z = y * b
pure $ z - 3
where
a = x + 1
b = a * 2

Is it possible to use the OpenStack.NET SDK with SoftLayer object storage?

SoftLayer Object Storage is based on the OpenStack Swift object store.
SoftLayer provide SDKs for their object storage in Python, Ruby, Java and PHP, but not in .NET. Searching for .NET SDKs for OpenStack, I came across OpenStack.NET.
Based on this question OpenStack.NET is designed for use with Rackspace by default, but can be made to work with other OpenStack providers using CloudIdentityWithProject and OpenStackIdentityProvider.
SoftLayer provide the following information for connecting to their Object Storage:
Authentication Endpoint
Public: https://mel01.objectstorage.softlayer.net/auth/v1.0/
Private: https://mel01.objectstorage.service.networklayer.com/auth/v1.0/
Username:
SLOS123456-1:email#example.com
API Key (Password):
1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef
It's not obvious how this would map to the fields of CloudIdentityWithProject, and OpenStackIdentityProvider but I tried the following and a few other combinations of project name / username / uri:
var cloudIdentity = new CloudIdentityWithProject()
{
ProjectName = "SLOS123456-1",
Username = "email#example.com",
Password = "1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",
};
var identityProvider = new OpenStackIdentityProvider(
new Uri("https://mel01.objectstorage.softlayer.net/auth/v1.0/"),
cloudIdentity);
var token = identityProvider.GetToken(null);
However, in all cases I received the following error:
Unable to authenticate user and retrieve authorized service endpoints
Based on reviewing the source code for SoftLayer's other language libraries and for OpenStack.NET, it looks like SoftLayer's object storage uses V1 auth, while OpenStack.NET is using V2 auth.
Based on this article from SoftLayer and this article from SwiftStack, V1 auth uses a /auth/v1.0/ path (like the one provided by SoftLayer), with X-Auth-User and X-Auth-Key headers as arguments, and with the response contained in headers like the following:
X-Auth-Token-Expires = 83436
X-Auth-Token = AUTH_tk1234567890abcdef1234567890abcdef
X-Storage-Token = AUTH_tk1234567890abcdef1234567890abcdef
X-Storage-Url = https://mel01.objectstorage.softlayer.net/v1/AUTH_12345678-1234-1234-1234-1234567890ab
X-Trans-Id = txbc1234567890abcdef123-1234567890
Connection = keep-alive
Content-Length = 1300
Content-Type = text/html; charset=UTF-8
Date = Wed, 14 Oct 2015 01:19:45 GMT
Whereas V2 auth (identity API V2.0) uses a /v2.0/tokens path, with the request and response in JSON objects in the message body.
Based on the OpenStackIdentityProvider class in OpenStack.NET I hacked together my own SoftLayerOpenStackIdentityProvider like this:
using JSIStudios.SimpleRESTServices.Client;
using net.openstack.Core.Domain;
using net.openstack.Providers.Rackspace;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using OpenStack.Authentication;
using System;
using System.Linq;
using System.Collections.Generic;
namespace OpenStackTest1
{
public class SoftLayerOpenStackIdentityProvider : CloudIdentityProvider
{
public SoftLayerOpenStackIdentityProvider(
Uri urlBase, CloudIdentity defaultIdentity)
: base(defaultIdentity, null, null, urlBase)
{
if (urlBase == null)
throw new ArgumentNullException("urlBase");
}
public override UserAccess GetUserAccess(
CloudIdentity identity, bool forceCacheRefresh = false)
{
identity = identity ?? DefaultIdentity;
Func<UserAccess> refreshCallback =
() =>
{
// Set up request headers.
Dictionary<string, string> headers =
new Dictionary<string, string>();
headers["X-Auth-User"] = identity.Username;
headers["X-Auth-Key"] = identity.APIKey;
// Make the request.
JObject requestBody = null;
var response = ExecuteRESTRequest<JObject>(
identity,
UrlBase,
HttpMethod.GET,
requestBody,
headers: headers,
isTokenRequest: true);
if (response == null || response.Data == null)
return null;
// Get response headers.
string authToken = response.Headers.Single(
h => h.Key == "X-Auth-Token").Value;
string storageUrl = response.Headers.Single(
h => h.Key == "X-Storage-Url").Value;
string tokenExpires = response.Headers.Single(
h => h.Key == "X-Auth-Token-Expires").Value;
// Convert expiry from seconds to a date.
int tokenExpiresSeconds = Int32.Parse(tokenExpires);
DateTimeOffset tokenExpiresDate =
DateTimeOffset.UtcNow.AddSeconds(tokenExpiresSeconds);
// Create UserAccess via JSON deseralization.
UserAccess access = JsonConvert.DeserializeObject<UserAccess>(
String.Format(
"{{ " +
" token: {{ id: '{0}', expires: '{1}' }}, " +
" serviceCatalog: " +
" [ " +
" {{ " +
" endpoints: [ {{ publicUrl: '{2}' }} ], " +
" type: 'object-store', " +
" name: 'swift' " +
" }} " +
" ], " +
" user: {{ }} " +
"}}",
authToken,
tokenExpiresDate,
storageUrl));
if (access == null || access.Token == null)
return null;
return access;
};
string key = string.Format("{0}:{1}", UrlBase, identity.Username);
var userAccess = TokenCache.Get(key, refreshCallback, forceCacheRefresh);
return userAccess;
}
protected override string LookupServiceTypeKey(IServiceType serviceType)
{
return serviceType.Type;
}
}
}
Because some of the members of UserAccess (like IdentityToken and Endpoint) have no way to set their fields (the objects have only a default constructor and only read-only members), I had to create the UserAccess object by deserializing some temporary JSON in a similar format as returned by the V2 API.
This works, ie I can now connect like this:
var cloudIdentity = new CloudIdentity()
{
Username = "SLOS123456-1:email#example.com",
APIKey = "1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",
};
var identityProvider = new SoftLayerOpenStackIdentityProvider(
new Uri("https://mel01.objectstorage.softlayer.net/auth/v1.0/"),
cloudIdentity);
var token = identityProvider.GetToken(null);
And then get access to files etc like this:
var cloudFilesProvider = new CloudFilesProvider(identityProvider);
var containers = cloudFilesProvider.ListContainers();
var stream = new MemoryStream();
cloudFilesProvider.GetObject("testcontainer", "testfile.dat", stream);
However, is there a better way than this to use SoftLayer Object Storage from .NET?
I briefly also looked at the OpenStack SDK for .NET (a different library to OpenStack.NET), but it too seems to be based on V2 auth.

Grails findAllByRole() error

I am trying to send email to all users with admin role when list() action has been called.
Inside my list method I put the following code:
def admins = User.findAllByRole("ROLE_ADMIN")
//def approverEmails = User.findByRole("ROLE_APPROVER").collect { it.email }
notifierService.sendApproverRequestEmail(admins)
flash.message = message(code: 'default.created.message', args: [message(code: 'project.label', default: 'Project'), projectInstance.id])
redirect(action: "show", id: projectInstance.id)
But Grails doesn't recognize findAllByRole() method. What am I doing wrong? Is there any other way to send message from service when certain actions in controller are called.
Here is also my service code:
def sendApprovalRequestEmail( def users ) {
users.each { -> user
mailService.sendMail{
to user.email
from "padre#everyonecounts.com"
subject "New project needs approval."
body "Hi ${user.username}! " +
"New project has been requested and needs your approval."
}
}
}
Here is the error:
URI
/PaDRe/project/list
Class
org.codehaus.groovy.grails.exceptions.InvalidPropertyException
Message
No property found for name [role] for class [class com.everyonecounts.padre.User]
Around line 21 of grails-app\controllers\com\everyonecounts\padre\ProjectController.groovy
18: params.max = Math.min(params.max ? params.int('max') : 10, 100)
19: [projectInstanceList: Project.list(params), projectInstanceTotal: Project.count()]
20:
21: def admins = User.findAllByRole("ROLE_ADMIN")
22: //def approverEmails = User.findByRole("ROLE_APPROVER").collect { it.email }
23: notifierService.sendApproverRequestEmail(admins)
24:
Trace
Line | Method
->> 108 | methodMissing in org.grails.datastore.gorm.GormStaticApi
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 21 | list in ProjectController.groovy
| 895 | runTask . . . in java.util.concurrent.ThreadPoolExecutor$Worker
| 918 | run in ''
^ 662 | run . . . . . in java.lang.Thread
Here is my User class
package com.everyonecounts.padre
class User{
transient springSecurityService
String username
String password
String email
boolean enabled
boolean accountExpired
boolean accountLocked
boolean passwordExpired
static constraints = {
username blank: false, unique: true
password size: 5..80, blank: false
}
static mapping = {
password column: '`password`'
}
Set<Role> getAuthorities() {
UserRole.findAllByUser(this).collect { it.role } as Set
}
def beforeInsert() {
encodePassword()
}
def beforeUpdate() {
if (isDirty('password')) {
encodePassword()
}
}
protected void encodePassword() {
password = springSecurityService.encodePassword(password)
}
}
The problem you are having is because you don't understand the default spring security implementation. To get a list of users with a given role:
UserRole.findAllByRole(Role.findByAuthority("ROLE_ADMIN"))*.user
Your problem probably is that User.findAllByRole() is expecting a Role as the argument, not a String.
There is a relevant example in 'Querying Associations' subsection of http://grails.org/doc/2.2.x/guide/single.html#finders (shown below)
def author = Author.findByName("Stephen King")
def books = author ? Book.findAllByAuthor(author) : []