Skip to content

Instantly share code, notes, and snippets.

@rekire
Created March 13, 2024 21:12
Show Gist options
  • Save rekire/c3b5e1c65d6bf833a580c3d720992c64 to your computer and use it in GitHub Desktop.
Save rekire/c3b5e1c65d6bf833a580c3d720992c64 to your computer and use it in GitHub Desktop.
Sample implementation how to read and write credentials with lib secret
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <libsecret/secret.h>
#define SERVICE_NAME "your.service.name"
#define MY_SCHEMA getMySchema()
const SecretSchema* getMySchema (void){
static const SecretSchema mySchema = {
SERVICE_NAME, SECRET_SCHEMA_NONE,
{
{ "username", SECRET_SCHEMA_ATTRIBUTE_STRING },
{ "NULL", 0 },
},
// Fixing compile warning with a zero and NULLs
0, // reserved
NULL, // reserved1
NULL, // reserved2
NULL, // reserved3
NULL, // reserved4
NULL, // reserved5
NULL, // reserved6
NULL, // reserved7
};
return &mySchema;
}
int main(int argc, char **argv) {
GError *error = NULL;
GList *items = secret_password_search_sync(MY_SCHEMA, SECRET_SEARCH_ALL, NULL, &error, NULL);
printf("found %d items\n", g_list_length(items));
if (error != NULL) {
g_error("Error retrieving secret: %s", error->message);
g_error_free(error);
return EXIT_FAILURE;
} else if (g_list_length(items) > 0) {
/* The attributes used to lookup the password should conform to the schema. */
gchar *password = secret_password_lookup_sync(MY_SCHEMA, NULL, &error, NULL);
if (error != NULL) {
/* ... handle the failure here */
printf("Query password failed.\n");
g_error_free (error);
} else if (password == NULL) {
/* password will be null, if no matching password found */
printf("No password found\n");
} else {
GHashTable *attributes = secret_retrievable_get_attributes(items->data);
const gchar *username = g_hash_table_lookup(attributes, "username");
printf("Username: %s\nPassword: %s\n", username, password);
g_hash_table_unref(attributes);
g_list_free_full(items, g_object_unref);
secret_password_free(password);
}
}
/*
* The variable argument list is the attributes used to later
* lookup the password. These attributes must conform to the schema.
*/
secret_password_store_sync (MY_SCHEMA, SECRET_COLLECTION_DEFAULT,
"DemoApp", "example password", NULL, &error,
"username", "demo user",
NULL);
if (error != NULL) {
printf("error\n");
/* ... handle the failure here */
g_error_free (error);
} else {
printf("Password saved!\n");
}
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment